How-to: MyInvocation

The $MyInvocation automatic variable that contains an object with information about the current command, such as a script, function, or script block.

You can use the information in the object, such as the path and file name of the script ($MyInvocation.mycommand.path) or the name of a function ($ to identify the current command.

The script below demonstrates the use of MyInvocation, n.b. this must be run as a script not interactively at the command line:

" Display the full pathname of this running script:"
# This will return something like C:\demo\test.ps1
"`n Display the directory only (using a small function):"
function Get-ScriptDirectory
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path

$dir = Get-ScriptDirectory
# This will return something like C:\demo
# Optional - more detailed information
# "Display ALL the properties of $myinvocation"
# $myinvocation
# "`n Display the TYPE of this built-in array variable"
# $myinvocation.GetType()

‚ÄúDrive a nail home and clinch it so faithfully that you can wake up in the night and think of your work with satisfaction,- a work at which you would not be ashamed to invoke the Muse” ~ Henry David Thoreau

Related PowerShell Cmdlets

Automatic variables ($_, $Args etc)
Run a PowerShell script.

Copyright © 1999-2023
Some rights reserved