假设有一个名称为exampleService的应用程序,应该在Server1上运行。如果它在运行,这段代码就可以工作。然而当它没有运行时,它就会崩溃。
$application = Get-Process -ComputerName Server1 -Name "exampleService"
如果应用程序没有运行,我就会出现这种崩溃。有没有一种更优雅的方法来发现它是否没有运行(而不崩溃)?
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
另外,如果服务器没有运行,是否可以在服务器上启动应用程序?
服务器正在运行Windows Server 2012。PowerShell命令是在Windows 7 64位电脑上运行的。
看看使用 -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错误时继续,即进程未找到。 (我更倾向于使用TryCatch)。 但是我没有做过太多的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
}