Sunday, November 22, 2020

PowerShell: $Myinvocation.ScriptLineNumber behaves incorrectly with Class Methods

The PowerShell automatic variable, $Myinvocation, contains a ScriptLineNumber property. This property corresponds to the InvocationInfo class' ScriptLineNumber property  (see: InvocationInfo Class) which is defined as:


The property does not return the current line number but returns the line number that invoked the cmdlet (see PowerShell: Getting the Current Filename and Line Number). A PowerShell function is a form of cmdlet such as the following which contains FunctionA, FunctionB, and FuncntionC:



Note that each Write-Host makes use of the Subexpression Operator $() in order display the value of $Myinvocation.ScriptLineNumber (see: PowerShell: Expanding Object Properties in Strings using Subexpression Operator). The output of the above script is intuitive with each Write-Host displaying the line number invoking the current function/cmdlet:

The syntax to define classes was implemented in PowerShell 5.0. Classes contain methods and not functions. The previous code showing FunctionA, FunctionB, and FunctionC has been rewritten to as the equivalent code using class, ShowOffLineNumbers, and methods MethodA, MethodB, and MethodC (see the following):


Methods are not cmdlets so the value returned by $Myinvocation.ScriptLineNumber is not the line of code invoking the method is shown below (the scripts output):