判断Stop-Process在PowerShell中是否成功 [英] Tell if Stop-Process was successful or not in PowerShell

查看:224
本文介绍了判断Stop-Process在PowerShell中是否成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我在PowerShell中启动的过程如下:

Currently I start processes in PowerShell like this:

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

稍后再杀死它:

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

问题是,如果进程在调用$proc | Stop-Process之前就死了,那么PowerShell输出中将出现错误.我需要禁用此错误,而只是获取一个布尔值,该值指示Stop-Process是否已成功放入PowerShell脚本的变量中.如何在PS中获取此信息?

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?

推荐答案

使用$?变量确定最后执行的命令的成功或失败.设置$ErrorActionPreference变量以决定每个脚本如何处理错误输出,或者使用-ErrorAction参数根据每个命令进行设置:

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]
}

这篇关于判断Stop-Process在PowerShell中是否成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆