0

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!

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

WriteDebug and WriteVerbose needs additional parameter when using cmdlet. Is there anyway to get the output without the -Verbose or -Debug?
Not without polluting the output. Do you get any errors? Cmdlet.WriteDebug and Cmdlet.WriteVerbose shouldn't require anything more that the message text?
No errors, just no output if I don't turn on the debug output or without -Debug. I'd like to let me user do not need any further steps and no more parameters and then get the message which is not included in the output object.
Alright, I'm going to use WriteVerbose(), which will not need to ask for additional commands/statements, just -vb in the parameter list. Thanks!
Actually... you can set VerbosePreference. The effect of the user providing -Verbose is to set VerbosePreference inside the cmdlet. You can set it directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.