如何在PowerShell cmdlet中打印出调试消息,而不是将WriteObject打印为返回值?

时间:2016-08-18 20:29:51

标签: c# powershell

我尝试使用C#构建PowerShell cmdlet。在一个函数中,我想打印一行日志并返回一个对象。如果我在两个地方都使用<code>,我可以在PowerShell窗口中看到它们。但是,如果我使用变量来获取输出my cmdlet,它将同时获取字符串和对象。我怎么能让变量只获得我要返回的对象?

e.g。

WriteObject()

假设我的cmdlet名为public override void ExecuteCmdlet() { Dictionary<string, string> returnValue = new Dictionary<string, string>(); WriteObject("Debug Log"); // Print log // ... do something ... WriteObject(returnValue); // Return value } 。在PowerShell窗口中,如果我运行

foo

输出为2。

$ret = foo
$ret.Count

输出包含调试消息和字典。让$ret 包含字典的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:2)

使用WriteDebug()写入Debug信息流:

public override void ExecuteCmdlet()
{
    Dictionary<string, string> returnValue = new Dictionary<string, string>();
    WriteDebug("Debug Log"); // Print log

    // ... do something ...

    WriteObject(returnValue); // Return value
}
PS C:\> @(foo).Count
1
PS C:\> $DebugPreference = 'Continue' # show debug output, but don't halt exection
PS C:\> @(foo).Count
Debug Log
1
PS C:\> $ret = foo
Debug Log
PS C:\> $ret.Count
1

注意:如果目的是被动地提供诊断输出而不必中断执行,您也可以写入Verbose流(WriteVerbose()