[英]Redirecting output to $null in PowerShell, but ensuring the variable remains set
我有一些代碼:
$foo = someFunction
這會輸出一條警告消息,我想將其重定向到 $null:
$foo = someFunction > $null
問題是,當我這樣做時,在成功抑制警告消息的同時,它也有負面的副作用,即不使用 function 的結果填充 $foo。
如何將警告重定向到 $null,但仍保持 $foo 填充?
另外,如何將標准 output 和標准錯誤重定向到 null? (在 Linux 中,它是2>&1
。)
我更喜歡這種方式來重定向標准 output (本機 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 編寫警告消息,該 cmdlet 允許使用-WarningAction
參數或$WarningPreference
自動變量抑制警告消息。 一個 function 需要使用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:
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,這並不是很明顯。 在來回之后,我發現在$( )
中包裝一個命令並在包裝器工作后添加一個顯式重定向。
我嘗試過的其他任何東西都不會 - 我仍然不知道為什么,因為 PowerShell 文檔具有理想的質量(並且充滿了不一致......)
為了在啟動時導入所有模塊,我添加了以下內容。 這產生了一些標准錯誤 output 由 powershell 無法通過ErrorAction
或重定向放入 rest 而不使用包裝......
如果有人能詳細說明為什么,那將不勝感激。
# import installed modules on launch
$PsMods = $(Get-InstalledModule);
$($PsMods.forEach({ Import-Module -Name $_.Name -ErrorAction Ignore })) *> /dev/null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.