NonStatic NonStatic - 3 months ago 21
PowerShell Question

How could I print out a debug message in PowerShell cmdlet but not WriteObject as return value?

I try to build a PowerShell cmdlet with C#. In a function, I want to print one line log and return an object. If in both place I use

WriteObject()
, I could see them in the PowerShell window. But if I use a variable to get the output my cmdlet, it gets both the string and object. How could I let the variable only get the object I'm about to return?

e.g.

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

// ... do something ...

WriteObject(returnValue); // Return value
}


Assume my cmdlet named
foo
. In PowerShell window, if I run

$ret = foo
$ret.Count


The output is 2.

$ret


The output contains both the debug message and the dictionary. Any idea to let
$ret
contains the dictionary?

Thanks!

Answer

Use WriteDebug() to write to the Debug stream:

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

Note: you could also write to the Verbose stream (WriteVerbose()), if the purpose is to passively provide diagnostic output without necessarily interrupting execution