Search code examples
stringpowershellcomparison

Extract string without spacing in powershell cmdlet


I have some powershell script . Instead totalcmd* you can type another process you want.

$tc = get-process -Name totalcmd* | format-wide -property Name 
echo $tc
if ($tc -eq "Totalcmd64")
{
Stop-Process -Name totalcmd*
}
Start-Sleep 10

It doesn't work, I think, because, my $tc not equal to string "totalcmd". How can I remove unwanted spaces of cmdlet get-process -Name totalcmd* | format-wide -property Name output and compare strings correctly?


Solution

  • You do not end up with a string because you pipe to format-wide. These cmdlets are best for representing data on the screen. Instead select the property and use -ExpandProperty to return it as a string:

    $tc = get-process -Name totalcmd* | Select-Object -ExpandProperty Name 
    echo $tc
    ...