假设有一个名为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位PC运行。
答案 0 :(得分:2)
使用-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)
}
答案 1 :(得分:1)
您可以将ErrorAction
设置为SilentlyContinue
(别名为-ea 0
):
$application = Get-Process -ComputerName Server1 -Name "exampleService" -ea 0
现在您可以检查$application
并启动应用程序,如果它为null。
答案 2 :(得分:1)
我只希望脚本继续发生一个特定的Get-Process错误,即找不到进程。 (而且我更喜欢使用Try / Catch)。但是我并没有做太多的功能,也很难找到具体的错误。
一旦发现我可以查看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
}