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):











3 comments :

  1. I am a newbie to Powershell. Can you tell me how to create a PS function 'fnLn' (shorthand for function-Line-number) that I could use in write-host statements that I make to facilitate debugging, to show the line number as follows: write-host [pseudocode: fnLn] "`$(var_a) = $(var_a)"?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. See my post from November 10, 2023 which I believe shows you what you want.

      Delete