我有一个PowerShell高级功能使用的自定义类库。类库功能之一是自定义类中的静态方法,用于模仿称为Write-Verbose
的PowerShell Utilities.Write.Verbose()
。在我的类库中,只有其他类及其公共方法才调用它。这是该实用工具类的代码片段:
namespace Utilities
{
public class Write
{
public static void Verbose(string msg, string source)
{
ConsoleColor originalForeGroundColor = Console.ForegroundColor;
ConsoleColor originalBackGroundColor = Console.BackgroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.Black;
Console.Write("VERBOSE: {0} {1}{2}", source, msg, Environment.NewLine);
Console.ForegroundColor = originalForeGroundColor;
Console.BackgroundColor = originalBackGroundColor;
}
}
}
如您所见,无论主机是什么,我都只写到标准控制台。但是,当我需要捕获详细的输出时,Console.Write
不会捕获,也不会定向到PowerShells Verbose流。
我在访问RunSpace时遇到了其他一些示例代码,但是它没有显示任何详细输出:
using (PowerShell ps = PowerShell.Create(RunspaceMode.CurrentRunspace))
{
var _msg = string.Format("VERBOSE: {0} {1}{2}", source, msg, Environment.NewLine);
VerboseRecord verboseRecord = new System.Management.Automation.VerboseRecord(_msg);
ps.Streams.Verbose.Add(verboseRecord);
}
所以,我的问题是:是否有办法从C#类方法中获取host
或PSHost
对象,或者能够将字符串写入PowerShell的详细信息流?我的PowerShell模块针对Windows Management Framework 4.0,而类库针对.Net 4.6 Framework。