简体   繁体   English

是否有一种使用Write-Host在Powershell中记录当前行的方法?

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

I would like something like I remember from C++ macros where I could output the current line number. 我想从C ++宏中记得我可以输出当前行号的东西。 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. 我想在PowerShell中使用这样的东西,所以我可以告诉TFS 2015告诉我第6行有错误是什么意思,但第6行是注释。 Clearly what I see and what PowerShell "thinks" are line 6 differ. 很明显,我看到的和PowerShell“认为”的是第6行的不同之处。

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: 要测试它们,请将下面的代码保存在脚本文件中(让我们称之为“test.ps1”)并从您的PowerShell提示符中调用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM