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?
Your if-else construct is perfect, but change the if condition like below:
Initially you were comparing an object to the “svchost” which will evaluate to false. With the
-expandPropertyflag, 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
-eqis true if the array contains the other expression, in this case the “svchost”There are other “better” ways to check as well: