我希望每分钟后台运行一次powershell脚本,不能出现窗口。我该怎么做?
我希望每分钟后台运行一次powershell脚本,不能出现窗口。我该怎么做?
使用Windows任务计划程序,并像这样运行您的脚本:
powershell -File myScript.ps1 -WindowStyle Hidden
此外,创建脚本使其在特定用户帐户下运行,而不仅仅是在该用户登录时。否则,您将看到一个控制台窗口。
安排系统运行您的任务。下面的命令将安排一个脚本在后台运行而不显示powershell控制台窗口:
schtasks /create /tn myTask /tr "powershell -NoLogo -WindowStyle hidden -file myScript.ps1" /sc minute /mo 1 /ru System
/ru
开关允许您更改计划任务将在其中执行的用户上下文。
system
并点击“检查名称”,它应该会出现对象NT AUTHORITY\SYSTEM
。这是唯一一个可以防止在我的屏幕上显示一个PS窗口的解决方案。 - Frantumn也许这种情况适用。我们不会每分钟启动PowerShell可执行文件(这很昂贵)。相反,我们通过调用额外的脚本一次性启动它,并在其中调用工作脚本以实现每分钟运行一次(或在工作脚本退出或失败后等待一分钟)。
创建启动Invoke-MyScript.ps1:
for(;;) {
try {
# invoke the worker script
C:\ROM\_110106_022745\MyScript.ps1
}
catch {
# do something with $_, log it, more likely
}
# wait for a minute
Start-Sleep 60
}
从命令提示符(例如从启动.bat文件)运行此命令:
start /min powershell -WindowStyle Hidden -Command C:\ROM\_110106_022745\Invoke-MyScript.ps1
PowerShell 窗口由于使用了 `start /min` 命令而只会短暂地出现并被最小化,并很快就会完全隐藏。因此实际上只有任务栏图标会出现一会儿,而不是窗口本身。这并不算太糟糕。要创建一个后台PowerShell任务,运行一个每分钟重复一次且没有任何可见窗口的脚本,请以管理员身份运行PowerShell,然后使用Register-ScheduledJob
命令来运行你的脚本。以下是如何实现的示例:
Register-ScheduledJob -Name 'SomeJobName' -FilePath 'path\to\your\ps1' -Trigger (New-JobTrigger -Once -At "9/28/2018 0am" -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration ([TimeSpan]::MaxValue))
如果您想手动强制运行此作业(可能是为了故障排除),则可以使用 Get-ScheduledJob
cmdlet,如下所示:
(Get-ScheduledJob -Name 'SomeJobName').StartJob()
while ($true) {<insert command(s) here>;start-sleep 2}
我对PowerShell是新手,所以如果你有反馈,请温柔一些;-)。
在任务计划程序属性的[常规]选项卡中,选择“无论用户是否登录”单选按钮可防止窗口在我的Windows 7机器上出现。
1) Open Schedule tasks from control panel.
2) Select Task Scheduler Library from left side window.
3) select Create Task from right side window.
4) Enter Name in General tab (any name).
5) Open Triggers tab -> New
6) Select interval as needed.Use Advanced settings for repeat task.
7) Open Actions tab ->New
8) Copy/Paste following line in Program/script *
* Here D:\B.ps1 in code is path to my B.ps1 file
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe D:\B.ps1
的意思是在 Windows 上运行 PowerShell,然后执行 D 盘上的 B.ps1 文件。9) ok and apply changes
10) Done!
# Filecheck.ps1
# Version 1.0
# Use this to simply test for the existance of an input file... Servers.txt.
# I want to then call another script if the input file exists where the
# servers.txt is neded to the other script.
#
$workpath=".\Server1\Restart_Test"
# Created a functon that I could call as part of a loop.
function Filecheck
{
if (test-path $workpath\servers.txt)
{
rename-item $workpath\servers.txt servers1.txt
"Servers.txt exist... invoking an instance of your script agains the list of servers"
Invoke-Expression .\your_Script.ps1
}
Else
{
"sleeping"
Start-Sleep -Seconds 60
}
}
Do
{
Filecheck
$fred=0
# Needed to set a variabe that I could check in the while loop.
# Probably a better way but this was my way.
}
While( $fred -lt 1 )