我正在编写一些自动化脚本,需要使用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显然会抛出错误(比如无法到达机器),但输出总是正确的。
有没有办法知道命令是否成功运行?
发布于 2014-10-02 06:08:54
system(...)实际上会返回一个值,说明它是否成功,而不是调用的输出。
所以你可以简单地说
success = system("powershell.exe #{powershell_command}")
if success then
...
end如果需要输出和返回代码,可以使用backticks和query $?获取退出状态(顺便说一句,不是问题注释中链接到的$? )。
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
发布于 2015-08-11 02:13:18
还有另一种选择,那就是从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我将stdout与true进行比较,但您可以将其与您需要的任何内容进行比较。described in blog
https://stackoverflow.com/questions/26134810
复制相似问题