我遇到了一些问题,无法重定向非 .NET 程序集方法调用的输出:
在下面的代码中,您可以看到使用 .NET 类 System.Net.Dns 的一个成功的重定向和两个失败的重定向。
其中一个是内联的 C# 类型,另一个是 VS 编译的 .dll,它只包含与 $cs_code 代码块相同的内容。
目前我的唯一解决办法是使用 [Console]::SetOut 和 [Console]::SetError 捕获其输出。
但是为什么它们会失败,如何重定向/捕获这些流输出?
# .NET Version 4.7.2
# PSVersion 5.1.16299.431
# PSEdition Desktop
# PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
# BuildVersion 10.0.16299.431
# CLRVersion 4.0.30319.42000
# WSManStackVersion 3.0
# PSRemotingProtocolVersion 2.3
# SerializationVersion 1.1.0.1
if ($psISE) { cls }
$cs_code = @"
using System;
static public class demo
{
static public void go()
{
Console.WriteLine("***Console.WriteLine***");
Console.Out.WriteLine("***Console.Out.WriteLine***");
//Console.Out.Flush(); // no effect here
Console.Error.WriteLine("***Console.Error.WriteLine***"); // no output in ISE !
//Console.Error.Flush(); // no effect here
}
}
"@
Add-Type -TypeDefinition $cs_code -Language CSharp
#[Console]::SetOut((New-Object IO.StringWriter)) # this would catch all stdout
#[Console]::SetError((New-Object IO.StringWriter)) # this would catch all stderr
&{ [demo]::go() } 1> $null 2> $NULL # no redirection, why ?
# &{ [System.Net.Dns]::Resolve('bla') } 2> $NULL # works as expected
exit 0
Add-Type -AssemblyName 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' `
-ErrorAction Stop
Add-Type -Path "c:\_ClassLibraryDemo.dll" `
-ErrorAction Stop
&{ [MyLib.Demo]::Go() } 1> $null 2> $null // no effect here
Console.Out
或Console.Error
,当然也不会重定向它们。 - user4003407[Console]
API只需简单地打印到控制台,除非通过.SetOut()
/ 和.SetError()
方法应用显式重定向,否则同一进程中的其他代码 - 无论是C#还是PowerShell - 都看不到该输出。 - mklement0