2

Why does $MyInvocation.MyCommand.Name give you the name of the function when executed from within a function? According to this it is meant to give you the script file name. Here is the code I'm using:

function startScript
{
    $ScriptName = $MyInvocation.MyCommand.Name
    $ScriptName
}

$ScriptName = $MyInvocation.MyCommand.Name
$ScriptName

startScript

<#
Output:

testing.ps1
startScript
#>
Community
  • 1
  • 1
David Klempfner
  • 8,700
  • 20
  • 73
  • 153

1 Answers1

5

According to PowerShell documentation:

$MyInvocation
       Contains an information about the current command, such as the name, 
       parameters, parameter values, and information about how the command was
       started, called, or "invoked," such as the name of the script that called
       the current command. 

       $MyInvocation is populated only for scripts, function, and script blocks. 
       You can use the information in the System.Management.Automation.InvocationInfo
       object that $MyInvocation returns in the current script, 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. 
       This is particularly useful for finding the name of the current script.

Also see the following paragraph if you are interested in the script path:

   Beginning in Windows PowerShell 3.0, $MyInvocation has the following new
   properties. 

   -- PSScriptRoot: Contains the full path to the script that invoked the
      current command. The value of this property is populated only when
      the caller is a script.  
David Brabant
  • 41,623
  • 16
  • 83
  • 111