IF Else statement running the opposite of the way it should.

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Mike Mike 2 years, 3 months ago.

  • Author
    Posts
  • #18428
    Profile photo of Mike
    Mike
    Participant

    I'm having a problem properly running an [i]if else[/i] statement. [i]$service2[/i] is the [i]WinRM[/i] service and the [i]Get-Service[/i] cmdlet properly evaluates the whether the WinRM service is running or not.. If the [i]WinRM [/i] service is [u]stopped[/u] and the first part of the statement evaluates as [i]true[/i], the program runs the code under the [i]else[/i] statement. If I change the operator from [i]-eq[/i] to [i]-ne[/i], which would evaluate to [u]false[/u], the custom antimalware scan does not run run and PowerShell displays: [i]Cannot run custom antimalware scan — WinRM service is stopped.[/i] When I flip it, where the [i]WinRM[/i] service is running and the custom antimalware scan is supposed to run if the service is running and if it is not, it should display: [i]Cannot run custom antimalware scan — WinRM service is stopped[/i]; I get the the same error. Any thoughts about what I am doing wrong?

    Get-Service -computername $computer -name $service2
    
    if ($service2.Status -eq "Stopped") 
    
        {Write-Host "Cannot run custom antimalware scan -- WinRM service is stopped."}
    
    else 
    
        {Invoke-Command -computername $computer {& "C:\Program Files\Microsoft Security Client\Antimalware\MpCmdRun.exe" -scan -scantype 3 -File C:\ProgramData\Microsoft\Search\Data\Applications\Windows\}}
  • #18432
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    $service2 appears to be a string variable in your code. You haven't assigned the result of the call to Get-Service to any variable (and it's this result that has the Status property you'd be checking). For example:

    $serviceObject = Get-Service -ComputerName $computer -Name $service2
    
    if ($serviceObject.Status -eq 'Stopped') # ... etc
    
    • #18491
      Profile photo of Mike
      Mike
      Participant

      Thank You!! That fixed it.

You must be logged in to reply to this topic.