programing

PowerShell에서 출력을 $null로 리디렉션하지만 변수가 설정된 상태로 유지되도록 합니다.

i4 2023. 4. 11. 21:40
반응형

PowerShell에서 출력을 $null로 리디렉션하지만 변수가 설정된 상태로 유지되도록 합니다.

몇 가지 코드가 있습니다.

$foo = someFunction

그러면 $null로 리다이렉트하는 경고 메시지가 출력됩니다.

$foo = someFunction > $null

문제는 이렇게 하면 경고 메시지를 성공적으로 억제하면서 함수의 결과로 $foo가 채워지지 않는 부정적인 부작용도 발생한다는 것입니다.

경고를 $null로 리다이렉트하면서 $foo를 계속 입력하려면 어떻게 해야 합니까?

또, 표준 출력과 표준 에러를 모두 null로 리다이렉트 하려면 어떻게 해야 합니까(Linux에서는2>&1.)

표준 출력(네이티브 PowerShell)을 리다이렉트하려면 이 방법을 사용합니다.

($foo = someFunction) | out-null

하지만 이것 또한 효과가 있습니다.

($foo = someFunction) > $null

"some Function"의 결과로 $foo를 정의한 후 표준 오류만 수정하려면 다음 절차를 수행합니다.

($foo = someFunction) 2> $null

이는 위에서 언급한 것과 사실상 동일합니다.

또는 "someFunction"에서 표준 오류 메시지를 리다이렉트하고 그 결과로 $foo를 정의하려면 다음과 같이 하십시오.

$foo = (someFunction 2> $null)

양쪽을 리다이렉트 하려면 , 다음의 몇개의 옵션이 있습니다.

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

부록:

(Windows) powershell에는 Linux 기반 OS보다 더 많은 스트림이 있습니다.다음은 MS 문서 목록입니다.

여기에 이미지 설명 입력

따라서 와일드카드를 사용하여 모든 스트림을 리다이렉트할 수 있습니다.*>$null파일 대신 파일을 사용할 수도 있습니다.$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는 대응하는 메시지 유형에 대해 동일한 기능을 제공합니다.

기능 사용:

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 *.*" } }

최근 Linux 호스트에서 파워셸을 종료해야 했는데, 이는 쉽게 알 수 있는 일이 아니었습니다.앞뒤로 살펴보니 명령어를 랩핑하여$( )래퍼 작동 후 명시적 리다이렉션을 추가합니다.

PowerShell Docs의 품질은 바람직한 수준(불일관성이 가득)이기 때문에 다른 방법을 시도해도 이유는 알 수 없습니다.

부팅 시 모든 모듈을 Import하기 위해 다음과 같이 추가하였습니다.이로 인해 powershell에 의해 정지할 수 없는 stderr 출력이 생성되었습니다.ErrorAction또는 포장을 사용하지 않고 리다이렉트할 수도 있습니다.

왜 그런지 설명해주시면 감사하겠습니다.

 # import installed modules on launch 
 $PsMods = $(Get-InstalledModule); 
 $($PsMods.forEach({ Import-Module -Name $_.Name -ErrorAction Ignore })) *> /dev/null 

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

반응형