Syntax Hell: Check PowerShell Command Output in Ruby (Chef)

I ran into this while creating an LWRP, and while the code below addresses a very straightforward need, the syntax is anything but straightforward, and is definitely worth documenting.

I am running a one line PowerShell command that outputs True or False, and I want my Ruby method return value to be the same as PowerShell command return value.
Reading the output from the powershell_script is not easy, so instead I am going to run my PowerShell command from the cmd and read the shell_out, and then compare the stdout of the command to “true” or “false”.
The code below is the most simplistic example:

def powershell_output_true?()
  ps_command = "(1+1) -eq 2"
  cmd_str = "powershell -Command " " + ps_command + " " "
  cmd = shell_out(cmd_str, { :returns => [0] })
  if(cmd.stdout =~ /true/i)
     Chef::Log.debug "PowerShell output is true"
    return true
  else
    Chef::Log.debug "PowerShell output is false"
    return false
  end
end

 
To compare stdout to a custom string:

def powershell_output_expected?()
  ps_command = "\"sum = {0}\" -f (1+2)"
  cmd_str = "powershell -Command " " + ps_command + " " "
  cmd = shell_out(cmd_str, { :returns => [0] })
  if(cmd.stdout =~ /sum = 3/i)
    Chef::Log.debug "PowerShell output is as expected"
    return true
  else
    Chef::Log.debug "PowerShell output is not as expected"
    return false
  end
end

The triple backslash here is to escape a quote inside of the PowerShell command. The output of the command is “sum = 3” .

Hope this saves you an hour or two of debugging from hell 🙂
And one for the road:

syntax

Leave a Reply

Your email address will not be published. Required fields are marked *