programing

PowerShell의 변수에서만 오류 출력을 캡처하는 방법

cafebook 2023. 8. 16. 22:37
반응형

PowerShell의 변수에서만 오류 출력을 캡처하는 방법

PowerShell 명령의 stderr 출력을 변수에 저장하려고 합니다.파일에 저장하고 싶지 않고 표준 출력이 포함되지 않고 오류 출력만 포함되기를 원합니다.

이름이 지정된 파일로 리디렉션됩니다.error.txt:

$command $params 2> error.txt

그러면 stderr과 stdout이 모두 $output 변수로 리디렉션됩니다.

$output = & $command $params 2>&1

그러나 오류 출력만 변수(오류 내용과 동일)에 저장하려고 합니다.파일에 아무것도 쓰지 않고 txt 파일 위).그걸 어떻게 하는 거죠?

명령을 약간 다른 방법으로 호출하고 다음을 사용할 수 있습니다.-ErrorVariablePowerShell의 매개 변수:

Invoke-Expression "$command $params" -ErrorVariable badoutput

$badoutput이제 오류 문자열의 내용을 포함합니다.

여기 하위 표현을 사용한 사이먼 월린의 더 간단한 해결책이 있습니다.

$output = & $command $params 2>&1

다음과 같습니다.

$errOutput = $( $output = & $command $params ) 2>&1

arco444에 추가하려면 다음을 사용하여 특정 예외를 얻을 수 있습니다.$badoutput[0].Exception.

-ErrorAction-ErrorVariable에는 PowerShell에 내장된 ErrorAction 및 ErrorVariable 매개 변수를 효과적으로 사용하는 방법에 대한 자세한 내용이 나와 있습니다.

다음은 이 기능을 가장 쉽게 보여주는 방법입니다.

PS> Stop-Process 13,23
Stop-Process : Cannot find a process with the process identifier 13.
At line:1 char:13
+ Stop-Process  <<<< 13,23
Stop-Process : Cannot find a process with the process identifier 23.
At line:1 char:13
+ Stop-Process  <<<< 13,23

PS> Stop-Process 13,23 -ErrorAction Stop  # Only 1 error
Stop-Process : Command execution stopped because the shell variable “ErrorA
ctionPreference” is set to Stop: Cannot find a process with the process ide
ntifier 13.
At line:1 char:13
+ Stop-Process  <<<< 13,23 -ErrorAction Stop  # Only 1 error

PS> Stop-Process 13,23 -ErrorAction silentlycontinue  # No errors

PS> Stop-Process 13,23 -ErrorAction inquire  # ASK
Confirm
Cannot find a process with the process identifier 13.
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help
(default is “Y”):h
Stop-Process : Command execution stopped because the user selected the Halt
 option.
At line:1 char:13
+ Stop-Process  <<<< 13,23 -ErrorAction inquire  # ASK
PS>
PS>
PS> Stop-Process 13,23 -ErrorVariable a -ErrorAction SilentlyContinue

PS> $a[0]
Stop-Process : Cannot find a process with the process identifier 13.
At line:1 char:13
+ Stop-Process  <<<< 13,23 -ErrorVariable a -ErrorAction SilentlyContinue

PS> $a[0] |fl * -Force

Exception             : Microsoft.PowerShell.Commands.ProcessCommandExcepti
                        on: Cannot find a process with the process identifi
                        er 13.
TargetObject          : 13
CategoryInfo          : ObjectNotFound: (13:Int32) [Stop-Process], ProcessC
                        ommandException
FullyQualifiedErrorId : NoProcessFoundForGivenId,Microsoft.PowerShell.Comma
                        nds.StopProcessCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo

PS> $a |ft TargetObject -force -auto
TargetObject
————
          13
          23

사람들이 잘 알지 못하는 한 가지 사실은 ErrorVariable의 변수 이름 앞에 "+"를 지정하면 오류를 해당 변수에 추가할 수 있다는 것입니다.

PS> $err=@()
PS> stop-process 13 -ea silentlycontinue -ErrorVariable err
PS> $err.count
1

PS> stop-process 23 -ea silentlycontinue -ErrorVariable +err
PS> $err.count
2
PS> $err
Stop-Process : Cannot find a process with the process identifier 13.
At line:1 char:13
+ stop-process  <<<< 13 -ea silentlycontinue -ErrorVariable err
Stop-Process : Cannot find a process with the process identifier 23.
At line:1 char:13
+ stop-process  <<<< 23 -ea silentlycontinue -ErrorVariable +err

마지막으로 –ErrorAction 또는 –ErrorVariable을 입력할 필요가 없습니다. 이들에 대한 매개 변수 별칭이 정의되어 있으므로 그냥 입력할 수 있습니다.–EA그리고.-EV.

언급URL : https://stackoverflow.com/questions/27861176/how-to-capture-error-output-only-in-a-variable-in-powershell

반응형