몇 가지 코드가 있습니다.
$foo = someFunction
이것은 $ null로 리디렉션하려는 경고 메시지를 출력합니다.
$foo = someFunction > $null
문제는 내가 이것을 할 때 경고 메시지를 성공적으로 억제하면서도 함수의 결과로 $ foo를 채우지 않는 부정적인 부작용이 있다는 것입니다.
경고를 $ null로 리디렉션하지만 여전히 $ foo는 채워져 있습니까?
또한 표준 출력과 표준 오류를 모두 null로 리디렉션하는 방법은 무엇입니까? (Linux에서는 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-Warning
cmdlet을 사용하여 작성해야 합니다. 이렇게 하면 -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는 해당 메시지 유형에 대해 유사한 기능을 제공합니다.
답변
함수 사용 :
function run_command ($command)
{
invoke-expression "$command *>$null"
return $_
}
if (!(run_command "dir *.txt"))
{
if (!(run_command "dir *.doc"))
{
run_command "dir *.*"
}
}
또는 한 줄짜리를 좋아한다면 :
function run_command ($command) { invoke-expression "$command "|out-null; return $_ }
if (!(run_command "dir *.txt")) { if (!(run_command "dir *.doc")) { run_command "dir *.*" } }
답변
