ProgramingTip

PowerShell에서 출력을 $ null로 리디렉션하지만 변수가 설정되어 있는지 확인

bestdevel 2020. 11. 10. 22:05
반응형

PowerShell에서 출력을 $ null로 리디렉션하지만 변수가 설정되어 있는지 확인


몇 가지 코드가 있습니다.

$foo = someFunction

이것은 $ null로 리디렉션하려는 경고 메시지를 출력합니다.

$foo = someFunction > $null

부작용은 내가 할 때 경고 메시지를 문제로 제한 함수의 결과로 $ foo를 채우지 않는 것입니다.

경고를 $ null로 리디렉션하지만 여전히 $ foo는 채워져 있습니까?

또한 표준 출력과 표준 오류를 모두 null로 리디렉션하는 방법은 무엇입니까? (리눅스에서는 2>&1.)


표준 출력 (기본 PowerShell)을 리디렉션하는 데이 방법을 선호합니다.

($foo = someFunction) | out-null

그러나 이것도 작동합니다.

($foo = someFunction) > $null

"someFunction"의 결과로 $ foo를 정의한 후 표준 오류 만 리디렉션 다음을 수행하십시오.

($foo = someFunction) 2> $null

이것은 동일합니다.

또는 "someFunction"에서 표준 오류 메시지를 리디렉션 한 다음 결과로 $ foo를 정의합니다.

$foo = (someFunction 2> $null)

둘 다 리디렉션 몇 가지 옵션이 있습니다.

2>&1>$null
2>&1 | out-null

작동합니다.

 $foo = someFunction 2>$null

숨기고 싶은 오류라면 이렇게 할 수 있습니다

$ErrorActionPreference = "SilentlyContinue"; #This will hide errors
$someObject.SomeFunction();
$ErrorActionPreference = "Continue"; #Turning errors back on

경고 메시지는 Write-Warningcmdlet을 사용하여 작성해야 합니다. 이렇게 하면 -WarningAction순서 변수 또는 $WarningPreference자동 변수 를 사용하여 경고 메시지를 표시하지 않을 수 있습니다 . CmdletBinding이 기능을 구현할 함수를 합니다.

function WarningTest {
    [CmdletBinding()]
    param($n)

    Write-Warning "This is a warning message for: $n."
    "Parameter n = $n"
}

$a = WarningTest 'test one' -WarningAction SilentlyContinue

# To turn off warnings for multiple commads,
# use the WarningPreference variable
$WarningPreference = 'SilentlyContinue'
$b = WarningTest 'test two'
$c = WarningTest 'test three'
# Turn messages back on.
$WarningPreference = 'Continue'
$c = WarningTest 'test four'

명령 프롬프트에서 더 짧게 만들려면 다음을 사용할 수 있습니다 -wa 0.

PS> WarningTest 'parameter alias test' -wa 0

Write-Error, Write-Verbose 및 Write-Debug는 해당 메시지 유형에 대해 기능을 제공합니다.

참고 URL : https://stackoverflow.com/questions/5881174/redirecting-output-to-null-in-powershell-but-ensuring-the-variable-remains-set

반응형