powershellline-numbers

How can output the pointer (line number) from running powershell script?


I am looking a way to get output the pointer (line number) from running powershell script and write into a selfmade Log-File.

function DebugMode {

param([int]$linenumber,[String]$message)
$Date = Get-Date -Format 'yyyyMMdd'
$logfilepath ="$scriptpath\Debug_$Date.log"

$Date  + " - "+ $linenumber + " - " +$message |  Out-File -FilePath $logfilepath -Append}

Solution

  • You might use the Get-PSCallStack cmdlet for this:

    function Write-Log ($Message) {
        $linenumber = (Get-PSCallStack)[1].ScriptLineNumber
        $Date = Get-Date -Format 'yyyyMMdd'
        $Date  + " - "+ $linenumber + " - " +$message
    }
    
    Write-Log 'test'
    
    20230104 - 7 - test