Comparing string not working, not sure what I did wrong

Hi:

I’m new to PowerShell. I wrote a simple PowerShell that if the remote service is not running, start it. Below is the code.

$status=get-service -ComputerName $rem_compute -name $rem_svc | Select-Object -Property status | format-table -HideTableHeaders
if ($status -ieq “Stopped”) {
# start a service
}

If I run $status=get-service -ComputerName $rem_compute -name $rem_svc | Select-Object -Property status | format-table -HideTableHeaders

It returns Stopped

however, whatever the reasons, the If statement is always false even that remote service is stopped.

thanks

Welcome! When you have a moment, please go back and format your code: Formatting your code: How to format code on PowerShell.org

Sometimes, funky things can happen if all the code isn’t formatted as code. Much appreciated!

It’s not working because you’re formatting the output. Don’t use Format-Table when trying to use it later. Only use Format commands to make it easier to read when viewing the output.

$status = Get-Service -ComputerName $rem_compute -name $rem_svc | Select-Object -ExpandProperty Status

I’d personally also not use ieq unless you really care about casing.

if ($status -eq 'Stopped') {
# start a service
}

Note on the first command I modified it to ‘ExpandProperty’ so you just get the value of Status (no ‘header’), so that way, $status will be just a string.

Looks like your solution works, I was wondering that my code was leaving some extra things in the $status. I was looking for how to get just the result without heading and blank lines,

thanks

1 Like