Tell if Stop-Process was successful or not in PowerShell

烈酒焚心 提交于 2020-01-02 20:48:49

问题


Currently I start processes in PowerShell like this:

$proc = Start-Process notepad -Passthru
$proc | Export-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')

to later on kill it like this:

$proc = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$proc | Stop-Process

The problem is that if the process died before I got to call $proc | Stop-Process, I will get error in the PowerShell output. I need to disable this error and just get the Boolean value indicating if Stop-Process was successfully into a PowerShell script's variable. How can I get this info in PS?


回答1:


Use the $? variable to determine the success or failure of your last executed command. Set $ErrorActionPreference variable to decide how error output is handled per script, or use -ErrorAction parameter to set it per command:

$proc = Import-Clixml -Path (Join-Path $ENV:temp 'processhandle.xml')
$proc | Stop-Process -ErrorAction SilentlyContinue
if($?) {
    #Success
    Write-host $proc " Stopped Successfully"
}
else {
    #Failure
    #Use $error variable to retrieve the message
    Write-Error $error[0]
}


来源:https://stackoverflow.com/questions/32017378/tell-if-stop-process-was-successful-or-not-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!