Question

Could someone help me log the actual PowerShell command issued along with arguments.

I have a cmdlet implemented in C# as follows

class GetMyCommand : PSCmdlet
{
    // parameter definitions
    ...

    void processRecord()
    {
        // Here I want print actual arguments passed to the cmdlet.
    }
}

if someone calls

Get-MyCommand -Name Hello -File "test.txt"

I just want to log the command in the processRecord function.

 "Get-MyCommand -Name Hello -File "test.txt""

Clearly I know the cmdlet name, but not sure how to print the exact string of arguments.

Environment.CommandLine works inside regular exes, but how to do the same in cmdlets

Thanks

Was it helpful?

Solution

Use the MyInvocation.Line property on PSCmdlet e.g.:

void ProcessRecord() {
    var line = this.MyInvocation.Line
}

OTHER TIPS

Have a look at the InvocationInfo object available as MyInvocation member on PSCmdlet. It provides info like Line, BoundParameters etc that will be of use to you.

http://msdn.microsoft.com/en-us/library/system.management.automation.invocationinfo_members(v=vs.85).aspx

I'll add a caveat to $PSCmdlet.MyInvocation.Line:

It only knows the SINGLE line that was passed in. I use it to get a count from the pipeline in my Get-MailboxTrustee.ps1 script, and I've discovered that while this works great:

$Mailboxes | .\Get-MailboxTrustee.ps1

This does not:

$Mailboxes |
.\Get-MailboxTrustee.ps1

If you inspect $PSCmdlet.MyInvocation.Line in this second example, you will see that it is just:

.\Get-MailboxTrustee.ps1 (completely missing the $Mailboxes | <new line> portion of my command)

Too bad there isn't a $PSCmdlet.MyInvocation.Line[s]. We know that PowerShell is obviously aware, so $PSCmdlet's implementation seems to be where the lack is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top