np-*_*ard 1 ruby powershell windows2012
我正在编写一些自动化脚本,需要使用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
Run Code Online (Sandbox Code Playgroud)
我可以传入基于Invoke-Command的ps1文件,一切都按预期工作.我运行命令时可以在控制台中看到输出.
唯一的问题是无法确定命令运行是否成功; 有时PowerShell显然会抛出错误(比如无法进入机器),但输出始终是真的.
有没有办法知道命令是否成功运行?
system(...) 实际上会返回一个值,表示如果成功,而不是调用的输出.
所以你可以简单地说
success = system("powershell.exe #{powershell_command}")
if success then
...
end
Run Code Online (Sandbox Code Playgroud)
如果你想要输出和返回代码,你可以使用`backticks`并查询$?退出状态($?顺便说一下,与问题的评论中的链接不同).
output = `powershell.exe #{powershell_command}`
success = $?.exitstatus == 0
Run Code Online (Sandbox Code Playgroud)
如果你想要一种更可靠的方式来逃避更好的事情,我会用 IO::popen
output = IO::popen(["powershell.exe", powershell_command]) {|io| io.read}
success = $?.exitstatus == 0
Run Code Online (Sandbox Code Playgroud)
如果问题是PowerShell本身没有出现错误,那么你应该看一下这个问题