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

在PowerShell中将输出重定向到$null,但确保变量保持设置,powershell,Powershell,我有一些代码: $foo = someFunction 这会输出一条警告消息,我想将其重定向到$null: $foo = someFunction > $null 问题是,当我这样做时,在成功抑制警告消息的同时,它还有一个负面的副作用,就是没有用函数的结果填充$foo 如何将警告重定向到$null,但仍然填充$foo 另外,如何将标准输出和标准错误重定向到null?(在Linux中,它是2>&1)这应该可以工作 $foo = someFunction 2>$null 我更喜欢

我有一些代码:

$foo = someFunction
这会输出一条警告消息,我想将其重定向到$null:

$foo = someFunction > $null
问题是,当我这样做时,在成功抑制警告消息的同时,它还有一个负面的副作用,就是没有用函数的结果填充$foo

如何将警告重定向到$null,但仍然填充$foo

另外,如何将标准输出和标准错误重定向到null?(在Linux中,它是
2>&1

这应该可以工作

 $foo = someFunction 2>$null

我更喜欢用这种方式重定向标准输出(本机PowerShell)

但这也行得通:

($foo = someFunction) > $null
要在使用“someFunction”的结果定义$foo后重定向标准错误,请执行以下操作

这实际上与上面提到的相同

或者重定向来自“someFunction”的任何标准错误消息,然后使用结果定义$foo:

$foo = (someFunction 2> $null)
要重定向这两个方向,您有几个选项:

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

应使用
Write Warning
cmdlet写入警告消息,该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为相应类型的消息提供了类似的功能。

如果要隐藏错误,可以这样做

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

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

是什么产生了警告信息?如果你是
someFunction
的作者,你可以适当地修改它。实际上,在BourneShell(Linux)中,它是
2>/dev/null 1>/dev/null
;您显示的重定向将stderr重定向到与stdout相同的位置——可能是
/dev/null
,也可能是一个常规文件。在我将语句包装在{大括号}中而不是(括号)中后,这个解决方案对我有效。我可能正在使用一个更新的PS版本。如果我们正在创建一个后台作业,我们需要对作业本身进行调整:
{myCommandWithAnyOutput&}| Out Null
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 *.*" } }