Skip to main content

Access Information About Your Command’s Invocation

Problem

You want to learn about how the user invoked your script, function, or script block.

Solution

To access information about how the user invoked your command, use the $myInvocation variable:

"You invoked this script by typing: " + $myInvocation.Line

Discussion

The $myInvocation variable provides a great deal of information about the current script, function, or script block—and the context in which it was invoked:

MyCommand

Information about the command (script, function, or script block) itself.

ScriptLineNumber

The line number in the script that called this command.

ScriptName

When in a function or script block, the name of the script that called this command.

Line

The verbatim text used in the line of script (or command line) that called this command.

InvocationName

The name that the user supplied to invoke this command. This will be different from the information given by MyCommand if the user has defined an alias for the command.

PipelineLength

The number of commands in the pipeline that invoked this command.

PipelinePosition

The position of this command in the pipeline that invoked this command.

One important point about working with the $myInvocation variable is that it changes depending on the type of command from which you call it. If you access this information from a function, it provides information specific to that function—not the script from which it was called. Since scripts, functions, and script blocks are fairly unique, information in the $myInvocation.MyCommand variable changes slightly between the different command types.

Scripts

Definition and Path

The full path to the currently running script

Name

The name of the currently running script

CommandType Always ExternalScript

Functions

Definition and ScriptBlock

The source code of the currently running function

Options The options (None, ReadOnly, Constant, Private, AllScope) that apply to the currently running function

Name

The name of the currently running function

CommandType Always Function

Script blocks

Definition and ScriptBlock

The source code of the currently running script block

Name

Empty

CommandType Always Script

Help Category