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 ($myinvocation.mycommand.name) 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:

#[test.ps1]
" Display the full pathname of this running script:"
$myinvocation.mycommand.path
# 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
$dir
# 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()

The Get-ScriptDirectory function can be added to any script where

‚Äú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)
$PSScriptRoot


 
Copyright © 1999-2020 SS64.com
Some rights reserved