我有一些代码:
$foo = someFunction
这会输出一个警告消息,我想要将其重定向到 $null:
$foo = someFunction > $null
问题是,当我这样做时(使用@操作符来抑制警告消息),虽然成功地抑制了警告消息,但也产生了负面效应,即未将$foo填充为函数的结果。如何将警告重定向到$null,同时保持$foo中的结果?此外,如何将标准输出和标准错误都重定向到null?(在Linux中,可以使用“2>&1”)?我有一些代码:
$foo = someFunction
这会输出一个警告消息,我想要将其重定向到 $null:
$foo = someFunction > $null
问题是,当我这样做时(使用@操作符来抑制警告消息),虽然成功地抑制了警告消息,但也产生了负面效应,即未将$foo填充为函数的结果。如何将警告重定向到$null,同时保持$foo中的结果?此外,如何将标准输出和标准错误都重定向到null?(在Linux中,可以使用“2>&1”)?我更喜欢使用此方式重定向标准输出(原生PowerShell)...
($foo = someFunction) | out-null
但这也可以:
($foo = someFunction) > $null
要在将$foo定义为"someFunction"的结果后仅重定向标准错误,请执行以下操作:
($foo = someFunction) 2> $null
这与上面提到的相同。
或者将来自“someFunction”的任何标准错误消息重定向,然后使用结果定义$foo:
$foo = (someFunction 2> $null)
要同时重定向,你有几个选项:
2>&1>$null
2>&1 | out-null
补充说明:
请注意,(Windows)PowerShell具有比基于Linux的操作系统更多的流。以下是来自微软文档的列表:
因此,您可以使用通配符*>$null
重定向所有流,并且还可以使用文件代替$null
。
{ myCommandWithAnyOutput & } | Out-Null
- arberg这应该可以运行。
$foo = someFunction 2>$null
如果你想隐藏错误,你可以这样做:
$ErrorActionPreference = "SilentlyContinue"; #This will hide errors
$someObject.SomeFunction();
$ErrorActionPreference = "Continue"; #Turning errors back on
警告信息应该使用Write-Warning
命令,这允许使用-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,这并不是那么容易弄清楚的。经过反复尝试,我发现将命令包装在$( )
中,并在包装后添加显式重定向可以解决问题。
其他任何我尝试的方法都行不通 - 我仍然不知道为什么,因为PowerShell文档质量很高(但充满了不一致性...)
为了在启动时导入所有模块,我添加了以下内容。这会产生一些stderr输出,无法通过ErrorAction
或重定向来消除,必须使用包装...
如果有人能详细说明原因,那将非常感激。
# import installed modules on launch
$PsMods = $(Get-InstalledModule);
$($PsMods.forEach({ Import-Module -Name $_.Name -ErrorAction Ignore })) *> /dev/null
2>/dev/null 1>/dev/null
;你所展示的重定向将 stderr 重定向到与 stdout 相同的位置 - 这可能是/dev/null
,也可能是一个常规文件。 - jpaugh