Command Type and Name

Sometimes I just need to write something down somewhere. That way, I might be able to find what I need when I need it. Have you been to my website? If so, then just maybe you already know this. Over the last many years, I’ve done this repeatedly. It’s basically why this place exists. Best part, it’s not just for me. It’s for me and the 196.5 people that have visited daily over the last 20 days, and those before them. That excludes weekends, of course, as only some of us PowerShell on the weekend.

As you may know, we have way to determine a command type and command name (think function and function name), from within a command itself, as it executes. I’m tired of looking for this code inside something I’ve already written, or figuring out again, and so here we are. I’ve given myself another chance to “remember” it sooner. Here’s how it’s done.

Function Get-CommandInfo {
    $CmdType = "$($MyInvocation.MyCommand.CommandType)"
    $CmdName = "$($MyInvocation.MyCommand.Name)"
    "The name of this $($CmdType.ToLower()) is $CmdName."
} # End Get-CommandInfo.

In the above function, we create two variables — $CmdType and $CmdName. These hold, as you might expect, the type of command we’re executing and the name of it, as well. These variables are made possible due to the $MyInvocation automatic variable. This variable holds a great deal of information. As you can tell, we’ve used the CommandType and Name nested properties that reside inside the MyCommand property. We then echo a string to include the two values we’ve derived from this variable.

PS > Get-CommandInfo
The name of this function is Get-CommandInfo.

And, there it is; the type and name returned. Now to remember that I’ve written about it here, for that next time I don’t feel like exploring the $MyInvocation variable again, or tracking down the use of these properties somewhere else. Enjoy your Wednesday.

Leave a Reply

Your email address will not be published. Required fields are marked *