使用PowerShell脚本检查是否存在正在运行的进程(如果出现错误)



我的PowerShell代码看到进程正在运行,每60秒就会写一条消息,说明它正在运行——这很好。当我终止进程时,它会每60秒写一次"进程正在运行"——当进程被消除时。不会在应用程序日志中写入事件的逻辑有什么问题?如果我启动脚本,并且在启动时进程没有运行,它就会工作。

while($true) {
If (( $(Get-WmiObject Win32_Process |findstr "MoveFilesToServer") -eq $null )) 
{
Write-EventLog -LogName Application -Source "MoveFilesToServer" -eventID 0018 -EntryType Error -Message "Move files process not running"
}
else { Write-Host 'process is running' } 
Start-Sleep -Seconds 60
}

您处于while true的无限循环中:

$gwmiArgs = @{
Class       = 'Win32_Process'
Filter      = 'CommandLine LIKE "%MoveFilesToServer%"'
ErrorAction = 'Ignore'
}
while (Get-WmiObject @gwmiArgs) {
'Process is running.'
Start-Sleep -Seconds 60
}
$writeEventLogArgs = @{
LogName   = 'Application'
Source    = 'MoveFilesToServer'
EventID   = 18
EntryType = 'Error'
Message   = 'Move files process not running!'
}
Write-EventLog @writeEventLogArgs

只要进程存在,此版本就会运行,如果不存在,则会写入事件日志。

相关内容

最新更新