2014-10-01 3 views
1

Ruby를 사용하여 원격 컴퓨터에서 PowerShell 명령을 실행해야하는 자동화 스크립트를 작성 중입니다. 루비에서 나는 다음 코드를 가지고있다.Ruby에서 PowerShell 출력 얻기

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입니다.

명령이 성공적으로 실행되었는지 알 수있는 방법이 있습니까?

+0

PowerShell 실행 후 자동 변수'$? '를 확인하십시오. http://technet.microsoft.com/en-us/library/hh847768.aspx – mudasobwa

답변

4

system(...) 실제로 성공한 경우 호출 결과가 아닌 값을 반환합니다. 당신은 출력과 모두 코드를 반환합니다

그래서 당신은 단순히 댓글에 링크대로 종료 상태 (동일하지 $?에 대한`backticks` 및 쿼리 $?를 사용할 수

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

을 말할 수있다 당신은 더 나은 일을 피할 것보다 신뢰할 수있는 방법을 원한다면 그런데 질문에.)

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

+0

그래서 내가 잘못하고 있지만 정답 : IO :: popen ([ "powershell.exe", 'Write-Host "물건을 쓴다" ')) {| io | io.read}'는''stuff stuff ''를 반환해야합니까? 왜냐하면 내가 이것을 실행할 때, powershell은 확실히 실행되지만, IO :: popen'에 의해 반환되는 것은 아무것도 없습니다 ... – Sancarn

1

또 다른 옵션이 있습니다 한 번 봐 가지고 있어야하고, 그 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