Powershell获取进程查询

Dan*_*711 2 powershell

我想编写一个简单的 If 语句来检查进程是否存在。如果它存在,就应该开始一些事情。

像这样,但工作..;)

If ((Get-Process -Name Tvnserver.exe ) -eq $True)
{ 
    Stop-Process tnvserver
    Stop-Service tvnserver
    Uninstall...
    Install another Piece of Software
}
Else
{
    do nothing
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Ans*_*ers 6

Get-Process不返回布尔值,并且列出的进程名称不带扩展名,这就是您的代码不起作用的原因。删除扩展名并检查结果是否$nullMusaab Al-Okaidi建议的那样,或者将结果转换为布尔值:

if ( [bool](Get-Process Tvnserver -EA SilentlyContinue) ) {
  # do some
} else {
  # do other
}
Run Code Online (Sandbox Code Playgroud)

如果您不希望脚本在进程未运行的情况下执行任何操作:只需省略else分支即可。