When experimenting with the information available through the $myInvocation variable, it is helpful to see how this information changes between scripts, functions, and script blocks. For a useful deep dive into the resources provided by the $myInvocation variable, review the output of Example 141.
Example 141. GetInvocationInfo.ps1
############################################################################## ## ## GetInvocationInfo.ps1 ## ## Display the information provided by the $myInvocation variable ## ############################################################################## param([switch] $preventExpansion)
## Define a helper function, so that we can see how $myInvocation changes ## when it is called, and when it is dotsourced function HelperFunction {
" MyInvocation from function:" ""*50 $myInvocation
" Command from function:" ""*50 $myInvocation.MyCommand
}
## Define a script block, so that we can see how $myInvocation changes ## when it is called, and when it is dotsourced $myScriptBlock = {
" MyInvocation from script block:" ""*50 $myInvocation
" Command from script block:" ""*50 $myInvocation.MyCommand
}
## Define a helper alias SetAlias gii GetInvocationInfo
Example 141. GetInvocationInfo.ps1 (continued)
## Illustrate how $myInvocation.Line returns the entire line that the ## user typed. "You invoked this script by typing: " + $myInvocation.Line
## Show the information that $myInvocation returns from a script "MyInvocation from script:" ""*50 $myInvocation
"Command from script:" ""*50 $myInvocation.MyCommand
## If we were called with the PreventExpansion switch, don't go ## any further if($preventExpansion) {
return }
## Show the information that $myInvocation returns from a function "Calling HelperFunction" ""*50 HelperFunction
## Show the information that $myInvocation returns from a dotsourced ## function "DotSourcing HelperFunction" ""*50 . HelperFunction
## Show the information that $myInvocation returns from an aliased script "Calling aliased script" ""*50 gii PreventExpansion
## Show the information that $myInvocation returns from a script block "Calling script block" ""*50 & $myScriptBlock
## Show the information that $myInvocation returns from a dotsourced ## script block "DotSourcing script block" ""*50 . $myScriptBlock
## Show the information that $myInvocation returns from an aliased script "Calling aliased script" ""*50 gii –PreventExpansion