如何在不崩溃的情况下判断特定 ProcessName 是否为 运行

How can I tell if a specific ProcessName is running without crashing

假设有一个名为 exampleService 的应用程序应该 运行ning 在 Server1 上。此代码在 运行ning 时有效。但是,当它不是 运行ning 时,它会崩溃。

$application = Get-Process -ComputerName Server1 -Name "exampleService"

如果应用程序不是 运行ning,我会遇到此崩溃。有没有更优雅的方法来确定它是否不是 运行ning(不会崩溃)

Get-Process : Cannot find a process with the name "exampleService". Verify the process name and call the cmdlet again.
At line:1 char:16
+ $application = Get-Process -ComputerName Server1 -Name "exampleService"
+                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Sampler:String) [Get-Process], ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

如果不是 运行ning,是否也可以在服务器上启动应用程序?

服务器是 运行ning Windows Server 2012。PowerShell 命令是 运行 来自 Windows 7 64 位 PC。

考虑使用 -ErrorAction SilentlyContinue 来避免显示该错误。如果应用程序不是 运行.

,您可以在 If 语句中使用它来启动应用程序

--更新为包括启动远程进程

If (-NOT (Get-Process -Computername Server1 -name "cmd" -ErrorAction SilentlyContinue)) { 
    Write-Host "Launch application"
    $application = "c:\windows\system32\cmd.exe" 
    $start = ([wmiclass]"\Server1\Root\CIMV2:win32_process").Create($application)
}

您可以将 ErrorAction 设置为 SilentlyContinue(别名为 -ea 0):

$application = Get-Process -ComputerName Server1 -Name "exampleService" -ea 0

现在您可以检查 $application 并在其为空时启动应用程序。

我只希望我的脚本在出现一个特定的 Get-Process 错误时继续,即找不到进程。 (我更喜欢使用 Try/Catch)。但是我没有做太多的 powershell,并且无法找到具体的错误。

一旦我发现我可以查看 FullyQualifiedErrorId 并将以下内容添加到常规 Catch 块中,我就找到了我想要的内容。

Write-Host ('FullyQualifiedErrorId: ' + $_.FullyQualifiedErrorId);

作为一个适用于我的情况的完整示例:

Try {
    $application = Get-Process -Name "exampleService" -ea Stop  #note the -ea Stop is so try catch will fire whatever ErrorAction is configured
} Catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
   If ($_.FullyQualifiedErrorId) {
     If ($_.FullyQualifiedErrorId -eq "NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand"){
        Write-Host "Presume not running. That is OK.";   # or you could perform start action here
     }
   }
   else {
     throw #rethrow other processcommandexceptions
   }
} Catch {
    # Log details so we can refine catch block above if needed
    Write-Host ('Exception Name:' + $_.Exception.GetType().fullname); # what to put in the catch's square brackets
    If ($_.FullyQualifiedErrorId) {
        Write-Host ('FullyQualifiedErrorId: ' + $_.FullyQualifiedErrorId); #what specific ID to check for
    }
    throw  #rethrow so script stops 
}