【问题标题】:Get PowerShell output in Ruby在 Ruby 中获取 PowerShell 输出
【发布时间】:2014-10-01 05:42:56
【问题描述】:

我正在编写一些自动化脚本,需要使用 Ruby 在远程机器上运行 PowerShell 命令。在 Ruby 中,我有以下代码:

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

我可以传入基于 Invoke-Command 的 ps1 文件,一切都按预期工作。当我运行命令时,我可以在控制台中看到输出。

唯一的问题是没有办法知道命令运行是否成功;有时 PowerShell 显然会抛出错误(例如无法访问机器),但输出始终为 true。

有没有办法知道命令是否运行成功?

【问题讨论】:

标签: ruby powershell windows2012


【解决方案1】:

system(...) 实际上会返回一个值,说明它是否成功,而不是调用的输出。

所以你可以简单地说

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

如果您想要输出和返回码,您可以使用 `backticks` 并查询 $? 以获取退出状态(顺便说一下,与问题评论中链接的 $? 不同。)

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

如果您想要一种更可靠的方式来更好地逃避事情,我会使用IO::popen

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

如果问题是 powershell 本身没有退出并出现错误,你应该看看this question

【讨论】:

  • 所以,如果我弄错了,请纠正我,但是:IO::popen(["powershell.exe", 'Write-Host "doing stuff"']) {|io| io.read} 应该返回"doing stuff"?因为当我运行它时,powershell 肯定会运行,但 IO::popen 没有返回任何内容...
【解决方案2】:

还有另一个选项,那就是从 cmd 运行 PowerShell。这是(很难弄清楚)语法:

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

我将标准输出与 true 进行比较,但您可以将其与您需要的任何内容进行比较。 described in blog

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 2013-12-26
    • 2012-08-12
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    相关资源
    最近更新 更多