Windows 任务计划程序以不同于其他任务的方式运行'at system startup'任务



我有一个需要全天候运行的powershell脚本。

为了确保它做到这一点,我在任务调度程序中创建了两个(几乎(相同的任务。其中一个在每天午夜启动任务,另一个设置为使用触发器"在系统启动时"运行。脚本设置为在午夜前一分钟退出。

到目前为止一切都很好,一切都很顺利。我所有的基地都被覆盖了。计划任务99%的时间都在处理脚本,"启动时"任务涵盖偶尔的电源故障

然而,当我查看流程细节时,我注意到了一个细微的差异。

如果我打开一个powershell会话,并使用这个-检查午夜开始的任务的pid

PS C:UsersElvis> get-wmiobject win32_process | where{$_.ProcessId -eq nnnn}

(其中nnnn是PID(我看到列出了很多细节,包括这个。。。。

CommandLine         : "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -NoExit -command "&c:myDirmyScript.ps1"

这是有道理的,这正是我在任务定义中所做的。

如果对启动时开始的任务做类似的事情,那么我只得到,而不是看到完整的命令行

CommandLine         :

这可能看起来并不重要,但我想在启动新副本时检查是否没有其他版本的脚本在运行。我通过在脚本中包含这一行来做到这一点。(基本上,它检查运行相同脚本名称但具有不同PID的其他powershell进程(

get-wmiobject win32_process | where{$_.processname -eq 'powershell.exe' -and $_.ProcessId -ne $pid -and $_.commandline -match 'myScript'}

我需要能够说服任务调度程序在进程详细信息中包含脚本名称,或者找到另一种方法来检查是否有另一个脚本副本已经在运行

使用我称之为";PID锁定文件";。将PID写入已知的文件路径,如果该文件已经存在,请检查PID。如果它已经在运行,则抛出错误或退出。当脚本退出时,让它删除该文件。

$lockfilePath = "pathtoscript.pid"
try {
if( Test-Path -PathType Leaf $lockFilePath ) {

$oldPid = ( Get-Content -Raw $lockfilePath ).Trim()
if( Get-Process -Id $oldPid -EA SilentlyContinue ) {
throw "Only one instance of this script can run at a time"
}
}
$PID > $lockfilePath
# Rest of your script goes within this try block
} finally {
# Add a catch block if you like but this finally code
# guarantees a deletion attempt will be made on the
# PID file whether the try block succeeds or errors
if( Test-Path -PathType Leaf $lockfilePath ) {
Remove-Item $lockfilePath -Force -EA Continue
}
}

最新更新