QuickTip: Determine current line number in PowerShell

When scripting it can be interesting to know which line of the script is currently being executed, to determine this we take a look at the $Myinvocation automatic variable. This variable contains the ScriptLineNumber property which can be used what the current line of the script is. We can try run the following code:

1
2
PS > $Myinvocation.ScriptlineNumber
0

Although the output is correct this is not the output we are looking for. In order to display the line numbers for a script or function the variable should be placed in a function. The reason for this is that it determines from which line its function has been invoke, it cannot determine that if accessed directly. The following code is :

1
2
3
4
5
6
7
Function Get-CurrentLine {
    $Myinvocation.ScriptlineNumber
}
# Some comments
Get-CurrentLine
$null
Get-CurrentLine

This will output the numbers 5 and 7 which correspond to the line numbers. This can be useful when implementing the Write-Debug and Write-Verbose parameters in your scripts or functions in order to establish at what position in the script you currently are.

Automatic Variables
Get-Help about_Automatic_Variables
Share

2 thoughts on “QuickTip: Determine current line number in PowerShell

    1. Jaap Brasser Post author

      Can you show me how you execute the code exactly. Also are you using the PowerShell ISE or the PowerShell console?

      Reply

Leave a Reply