Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a canned way to log the current line in Powershell with a Write-Host?

Tags:

powershell

I would like something like I remember from C++ macros where I could output the current line number. It was exactly the same code, but the preprocessor would replace the macro with the current line. I want something like this in PowerShell so I can tell what is meant when TFS 2015 tells me there was an error on line 6, but line 6 is a comment. Clearly what I see and what PowerShell "thinks" are line 6 differ.

like image 874
Blanthor Avatar asked Jan 29 '26 02:01

Blanthor


1 Answers

First, define the following aliases:

function Get-ScriptLineNumber { return $MyInvocation.ScriptLineNumber }
function Get-ScriptName { return $MyInvocation.ScriptName }

new-item alias:__LINE__ -value Get-ScriptLineNumber
new-item alias:__FILE__ -value Get-ScriptName 

To test them, save the code below in a script file (let's call it "test.ps1") and call it from your powershell prompt:

function Hello                                                              #1
{                                                                           #2
    param (                                                                 #3
            [parameter(Mandatory = $true)] [string] $receiver               #4
    )                                                                       #5
                                                                            #6
    $i = 0                                                                  #7
                                                                            #8
    # Say Hello                                                             #9
    # Another comment                                                       #10
    # and yet another one                                                   #11
                                                                            #12
    Write-Host "Line:" $(__LINE__) "File:" $(__FILE__) "Hello $receiver"    #13
}                                                                           #14

Hello "World"

When you'll run it, you'll get the following result:

Line: 13 File: D:\Temp\test.ps1 Hello World
like image 58
David Brabant Avatar answered Jan 30 '26 19:01

David Brabant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!