如何在模块内将控制台输出重定向到 PowerShell 输出?

How do I redirect Console Output to PowerShell Output within a module?

如果我正在编写一个二进制 PowerShell 模块,并且碰巧使用了一个写入 STDOUT (Console.Out) 的 .NET 库——是否有推荐的方法来 重新路由 控制台输出到 PowerShell 的输出流?

我可以通过 Console.SetOut(...) 设置我自己的 TextWriter 来拦截 Console.Out 然后用它做一些事情(即我可以用 StringWriter 缓冲输出和将来某个时候全部写出来,或者我可以编写自定义 TextWriter 将所有 Write 命令发送到 PowerShell 的 WriteObject).

我的问题是,PowerShell 库中是否已经有一些标准或推荐的做法来执行此操作或一些内置工具?

我通过 GitHub 询问了 PS 团队的问题,一般的回答是 TextWriter-to-WriteObject 方法是一种合理的方法:https://github.com/PowerShell/PowerShell/issues/4849

如果要输出到管道,请使用 WriteObject()WriteInformation()WriteDebug()WriteWarning() 向主机发送消息(字符串)。