简体   繁体   English

Powershell获取过程查询

[英]Powershell get-process query

I want to write a simple If Statement which checks if an Process Exists. 我想编写一个简单的If语句,检查一个进程是否存在。 If it Exists, something should start. 如果存在,则应该开始。

Like this, but working.. ;) 像这样,但是工作..;;)

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

Thanks 谢谢

Get-Process doesn't return a boolean value and the process name is listed without extension, that's why your code doesn't work. Get-Process不会返回布尔值,并且列出的进程名称不带扩展名,这就是为什么您的代码不起作用的原因。 Drop the extension and either check if the result is $null as Musaab Al-Okaidi suggested, or cast the result to a boolean value: 删除扩展名,或者按照Musaab Al-Okaidi的建议检查结果是否为$null ,或者将结果转换为布尔值:

if ( [bool](Get-Process Tvnserver -EA SilentlyContinue) ) {
  # do some
} else {
  # do other
}

If you don't want the script to do anything in case the process isn't running: just omit the else branch. 如果您不希望脚本在进程未运行的情况下执行任何操作:只需忽略else分支。

This will evaluate to true if the process doesn't exist: 如果该过程不存在,则评估为true:

(Get-Process -name Tvnserver.exe -ErrorAction SilentlyContinue) -eq $null

or if you want to change it you can negate the statement as follows: 或者,如果您要更改它,则可以按以下方式否定该语句:

-not ( $(Get-Process -name Tvnserver.exe -ErrorAction SilentlyContinue) -eq $null )

It's important to have have -ErrorAction SilentlyContinue to avoid any errors been thrown if a process doesn't exist. 必须具有-ErrorAction SilentlyContinue来避免进程不存在时引发任何错误,这一点很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM