.net - 执行 .net 方法时如何重定向 Powershell 中的错误输出?

标签 .net powershell redirect methods error-handling

为什么 powershell 流重定向不适用于 .Net 调用?我具体尝试以下操作:

[system.net.dns]::Resolve("bla") 2>$null

这应该将错误输出重定向到 null,但事实并非如此。有很多其他方法可以抑制错误,但为什么重定向不起作用?如何重定向 .net 输出?

最佳答案

There's tons of other ways to suppress the error, but why isn't redirection working? How do you redirect .net output?

将表达式放入 PowerShell 语言结构中,例如脚本 block :

&{ [System.Net.Dns]::Resolve('bla') } 2>$null

表达式的输出仍将按预期运行:

PS> $IPHost = &{ [System.Net.DNS]::Resolve('bla') } 2>$null
PS> $IPHost -eq $null
True
PS> $IPHost = &{ [System.Net.DNS]::Resolve('www.stackoverflow.com') } 2>$null
PS> $IPHost

HostName          Aliases                 AddressList
--------          -------                 -----------
stackoverflow.com {www.stackoverflow.com} {104.16.35.249, 104.16.33.249, 104.16.37.249, 104.16.36.249...}

关于.net - 执行 .net 方法时如何重定向 Powershell 中的错误输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35169045/

相关文章:

c# - 在以下情况下如何确保不发生内存泄漏

powershell - 使用 Powershell 查找字符并重命名文件名

webserver - Lighttpd:将域重定向到新域,包括路径

php - 我如何重定向表数组以在 php 中显示其值

C# - 使用 DataContractJsonSerializer 序列化常量

.net - 在 .NET 中对私有(private)方法进行单元测试的最佳实践是什么?

c# - 如何在 dotnetnuke 框架中创建 Web 应用程序?

powershell - 如何使用具有特权提升的grunt-shell运行命令?

powershell - 从批处理重定向到Powershell

php - 使用 .htaccess [自定义 URL] 进行页面重定向