1

我正在使用 PowerShell 每小时检查一次“ASA”进程是否正在运行。如果没有,则重新启动它。使用从下面链接中 jon Z 的答案中找到的代码片段,它运行良好。也许有点太好了?Powershell - 如果进程未运行,请启动它

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

在此处输入图像描述

这是我的脚本。我还让脚本仔细检查自身,如果发现进程未运行,则向我发送电子邮件,并将结果通过电子邮件发送给我。

# 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 是正确的。

在此处输入图像描述

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

4

1 回答 1

1

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

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

它总是创建的过程,如果还没有创建它,则没有检查。

你必须像这样改变它

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

if声明之后这样称呼它:

invoke-expression $start
于 2012-05-11T14:39:32.157 回答