PowerShell: how to get if else construct right?

24,628

Solution 1

Your if-else construct is perfect, but change the if condition like below:

(Get-Process | Select-Object -expand name) -eq "svchost"

Initially you were comparing an object to the "svchost" which will evaluate to false. With the -expandProperty flag, you are getting that property of the object, which is a string and can be properly compared to "svchost".

Note that in the above you are comparing array of strings, which contains the name of process, to "svchost". In case of arrays -eq is true if the array contains the other expression, in this case the "svchost"

There are other "better" ways to check as well:

if (Get-Process | ?{ $_.Name -eq "svchost"}) {
  Write-Host "seen"
}
else {
  Write-Host "not seen"
}

Solution 2

You can simply ask Get-Process to get the process you're after:

if (Get-Process -Name svchost -ErrorAction SilentlyContinue) 
{
  Write-Host "seen"
}
else 
{
  Write-Host "not seen"
}
Share:
24,628
jrara
Author by

jrara

Updated on August 04, 2022

Comments

  • jrara
    jrara over 1 year

    I'm trying to learn powershell and tried to construct a if else statement:

    if ((Get-Process | Select-Object name) -eq "svchost") {
        Write-Host "seen"
        }
        else {
        Write-Host "not seen"
        }
    

    This ends up into "not seen", although there is svchost processes. How to modify this to get correct results?

  • manojlds
    manojlds over 12 years
    But that will give error if no process is there. That is why I did not suggest it. Or complicate it with silentlycontinue
  • Shay Levy
    Shay Levy over 12 years
    I should have added that myself. Anyway, it's another way to introduce the user to the ErrorAction option.
  • Rich
    Rich over 12 years
    Just a hint for people not yet used to it: -ErrorAction SilentlyContinue can be abbreviated to -ea 0. Great for golfing and interactive use, if you need it. Don't use it in scripts, though.