np-hard
np-hard

Reputation: 5815

Get PowerShell output in Ruby

I am writing some automation script that needs to run PowerShell commands on a remote machine using Ruby. In Ruby I have the following code:

def run_powershell(powershell_command)
    puts %Q-Executing powershell #{powershell_command}-
    output =  system("powershell.exe  #{powershell_command}")
    puts "Executed powershell output #{output}"
end

I can pass in Invoke-Command based ps1 files and everything works as expected. I can see the output in the console when I run the command.

The only problem is that there is no way to find out if the command run was successful; sometimes PowerShell is clearly throwing errors (like not able to get to the machine), but the output is always true.

Is there a way to know if the command ran successfully?

Upvotes: 1

Views: 4872

Answers (2)

DivineOps
DivineOps

Reputation: 1686

There is another option, and that is running the PowerShell from cmd. Here is the (pretty hard to figure out) syntax:

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

I am comparing the stdout to true, but you can compare it to whatever you need. described in blog

Upvotes: 1

cobbal
cobbal

Reputation: 70703

system(...) will actually return a value saying if it succeeded, not the output of the call.

So you can simply say

success = system("powershell.exe  #{powershell_command}")
if success then
    ...
end

If you want both the output and return code, you can use `backticks` and query $? for the exit status (not the same $? as linked to in the comment to the question, by the way.)

output = `powershell.exe  #{powershell_command}`
success = $?.exitstatus == 0

If you want a more reliable way that will escape things better, I'd use IO::popen

output = IO::popen(["powershell.exe", powershell_command]) {|io| io.read}
success = $?.exitstatus == 0

If the problem is that powershell itself isn't exiting with an error, you should have a look at this question

Upvotes: 6

Related Questions