Search code examples
powershellwindows-serverazure-runbook

Why if statement isn't working in Powershell script?


I have a VM running Windows Server 2008 R2 with the Zabbix Agent installed. I want to run a specific block of code if it's running. I started the service manually. When I log in to VM, open a PowerShell Prompt and type in the following snippet, it works perfectly:

$ZABBIX_INSTALLED = Get-Service "Zabbix Agent"
If ($ZABBIX_INSTALLED) {
   Write-Host "It's running"
}
else {
   Write-Host "Zabbix Agent is not running"
}

The problem is when I try call this as a script, it never returns true even when the process is running normally (I checked it in Task Manager).

Any suggestion on what it's happening with the code? I appreciate any help.

PS: I'm passing this script via Azure Runbook by running Invoke-AzRunCommand and passing the script as parameter.


Solution

  • Bruno,

    This code will cover all 3 possible situations (Not Installed, Not Running, Running).

    Try {
    
      $ZABBIX_INSTALLED = (Get-Service "Zabbix Agent" -EA Stop).Status
      
      If ($ZABBIX_INSTALLED -eq "Running") {
         "Zabbix Agent: It's running"
      }
      else {
         "Zabbix Agent: is not running"
      }
    
    } 
    
    Catch {
      "Zabbix Agent: Not Installed!"
    }
    
    

    HTH