Retrieving the parameters used to run a script

2017/03/29 | less than 1 minute read |

Using $MyInvocation

If you want to show the invocation line used to invoke a powershell script or function, you can use the automatic variable called $MyInvocation and the property Line to retrieve this information

$MyInvocation.Line

Here is an example, assume you have the following powershell script called MyInvocation.ps1 with following content:

PARAM(
    $A,
    $B,
    $C
)
$myinvocation.line

If you execute the script using the following line:

.\MyInvocation.ps1 -A test -B test

It will output the following

.\MyInvocation.ps1 -A test -B test

As you can see, it is easy to retrieve the command used invoked with its parameters and values.

Using $PSCmdlet

If your script or function has the advanced features enabled, using [CmdletBinding()] or [parameter()] (on one of the parameters), you will be able to use $PSCmdlet.MyInvocation.Line to retrieve the same information.

Example, same script as above but with the [CmdletBinding()]

[CmdletBinding()]
PARAM(
    $A,
    $B,
    $C
)

$PSCmdlet.myinvocation.line

If I invoke the script using:

.\MyInvocation.ps1 -C test -B test

I will get the following output:

.\MyInvocation.ps1 -C test -B test

Note that $MyInvocation is still available.

Leave a Comment