Friday, November 10, 2023

PowerShell: Including Line Number in Write-Host

 I get a few comments on my blogs and today I received this comment on this post, PowerShell: $Myinvocation.ScriptLineNumber behaves incorrectly with Class Methods:

Here is a function that will include the same number as the Write-Host is on:

function Get-LineNumber {
    return "$($Myinvocation.ScriptLineNumber)"
}

Write-Host "$(Get-LineNumber): put your message here"

To see the line number of Write-Host consider the following screenshot:


When the above code is run (in this case Visual Studio Code using the PowerShell extension) the following is displayed showing the Write-Host is on line 5:

PS C:\Users\jann\Documents\PS> . 'C:\Users\jann\Documents\PS\Write-ExampleLineNumber.ps1'
5: put your message here