我想要像我记得的 C++ 宏那样的东西,我可以在其中输出当前行号。这是完全相同的代码,但预处理器会将宏替换为当前行。我想要在 PowerShell 中执行类似的操作,这样当 TFS 2015 告诉我第 6 行有错误,但第 6 行是注释时,我就可以知道这意味着什么。显然,我所看到的和 PowerShell “认为”的第 6 行有所不同。
首先,定义以下别名:
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
Run Code Online (Sandbox Code Playgroud)
要测试它们,请将下面的代码保存在脚本文件中(我们称之为“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"
Run Code Online (Sandbox Code Playgroud)
当您运行它时,您将得到以下结果:
Line: 13 File: D:\Temp\test.ps1 Hello World
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1789 次 |
| 最近记录: |