1

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?

1

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

So, correct me if I'm getting this wrong but: IO::popen(["powershell.exe", 'Write-Host "doing stuff"']) {|io| io.read} should return "doing stuff"? Because when I run this, the powershell definitely runs, but nothing is returned by IO::popen...
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.