Daniel4711
Daniel4711

Reputation: 422

Powershell get-process query

I want to write a simple If Statement which checks if an Process Exists. 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

Upvotes: 3

Views: 8920

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

Get-Process doesn't return a boolean value and the process name is listed without extension, that's why your code doesn't work. Drop the extension and either check if the result is $null as Musaab Al-Okaidi suggested, or cast the result to a boolean value:

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.

Upvotes: 7

Musaab Al-Okaidi
Musaab Al-Okaidi

Reputation: 3784

This will evaluate to true if the process doesn't exist:

(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.

Upvotes: 3

Related Questions