PowerShell进程检查启动了太多进程

时间:2012-05-11 14:28:02

标签: powershell scripting

我正在使用PowerShell执行每小时检查以查看“ASA”进程是否正在运行。如果没有,则重新启动它。使用jon Z在下面链接中的答案中找到的代码片段,它的工作效果很好。也许有点太好了? Powershell - if a process is not running, start it

我有一个计划任务,每小时运行一次这个脚本24小时。我注意到的问题是我有一堆ASA进程打开,当我只需要&想要1.

enter image description here

这是我的剧本。如果发现进程没有运行,我也会对脚本进行双重检查以向我发送电子邮件,并通过电子邮件向我发送结果。

# Set some variables
$computer = $env:COMPUTERNAME
$prog = "C:\Program Files\Avaya\Site Administration\bin\ASA.exe"
$procName = "ASA"
$running = Get-Process $procName -ErrorAction SilentlyContinue
$start = ([wmiclass]"win32_process").Create($prog) # the process is created on this line

# Begin process check
if($running -eq $null) { # evaluating if the program is running
    $start # Start the program
    sleep 5
    # Re-check the process to see if it is running
    $nowRunning = Get-Process $procName -ErrorAction SilentlyContinue
    # Email us the results as to whether it started or was not able to restart. 
    if ($nowRunning -eq $null) {
        blat.exe - -priority 1 -to john@doe.com -server my.smtp.com -f john@doe.com -subject "ASA cannot be restarted on $computer!" -body "The latest powershell check showed that ASA was not running on $computer! ||PowerShell was not able to restart ASA. Please investigate."
        } else { 
        blat.exe - -priority 1 -to john@doe.com -server my.smtp.com -f john@doe.com -subject "ASA was restarted on $computer!" -body "The latest powershell check showed that ASA was not running on $computer! ||PowerShell was able to automatically restart ASA."
    }
} 

我的第一个假设是进程名称错误,它应该是任务管理器中定义的程序名称。但是根据这个输出,只使用ASA,这是正确的。

enter image description here

所以我不知道为什么它会启动多个实例。

1 个答案:

答案 0 :(得分:1)

每次执行脚本时,都会在此行中创建进程:

$start = ([wmiclass]"win32_process").Create($prog) # the process is created on this line

它始终创建的过程,如果还没有,则无法创建它。

你必须像这样改变它

$start = '([wmiclass]"win32_process").Create($prog)'

并在if语句之后调用它:

invoke-expression $start