在PowerShell中将输出重定向到$null,但确保变量仍然设置

123

我有一些代码:

$foo = someFunction

这会输出一个警告消息,我想要将其重定向到 $null:

$foo = someFunction > $null
问题是,当我这样做时(使用@操作符来抑制警告消息),虽然成功地抑制了警告消息,但也产生了负面效应,即未将$foo填充为函数的结果。如何将警告重定向到$null,同时保持$foo中的结果?此外,如何将标准输出和标准错误都重定向到null?(在Linux中,可以使用“2>&1”)?

2
产生警告信息的是什么?如果您是“someFunction”的作者,您可以适当地进行更改。 - stej
1
实际上,在 Bourne Shell(Linux)中,它是 2>/dev/null 1>/dev/null;你所展示的重定向将 stderr 重定向到与 stdout 相同的位置 - 这可能是 /dev/null,也可能是一个常规文件。 - jpaugh
6个回答

207

我更喜欢使用此方式重定向标准输出(原生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的操作系统更多的流。以下是来自微软文档的列表:

MS文档链接:

enter image description here

因此,您可以使用通配符*>$null重定向所有流,并且还可以使用文件代替$null


1
在我将语句包裹在{花括号}中而不是(圆括号)后,这个解决方案对我起作用了。我可能正在使用更新的PS版本。 - ManEatingCheese
2
如果我们正在创建一个后台作业,我们需要让作业本身静默:{ myCommandWithAnyOutput & } | Out-Null - arberg

16

这应该可以运行。

 $foo = someFunction 2>$null

15

如果你想隐藏错误,你可以这样做:

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

6

警告信息应该使用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分别为它们对应消息类型提供了类似的功能。


1
使用一个函数:
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 *.*" } }

0

最近,我不得不在Linux主机上关闭powershell,这并不是那么容易弄清楚的。经过反复尝试,我发现将命令包装在$( )中,并在包装后添加显式重定向可以解决问题。

其他任何我尝试的方法都行不通 - 我仍然不知道为什么,因为PowerShell文档质量很高(但充满了不一致性...)

为了在启动时导入所有模块,我添加了以下内容。这会产生一些stderr输出,无法通过ErrorAction或重定向来消除,必须使用包装...

如果有人能详细说明原因,那将非常感激。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接