一个函数可以知道它的执行位置吗?

时间:2017-07-10 10:17:05

标签: powershell

$MyInvocation可用于标识脚本源的位置。

一个功能如何做同样的事情?

function whereami {
    Write-Host $MyInvocation.MyCommand.Path  # produces nothing
}

Write-Host $MyInvocation.MyCommand.Path
whereami

C程序员将使用__FILE__

1 个答案:

答案 0 :(得分:0)

$PSCommandPath返回正在执行的脚本的完整路径。

请注意,必须先将脚本另存为文件,然后才能在ISE中使用。

function whereami {
    $PSCommandPath
}

Write-Host $MyInvocation.MyCommand.Path
whereami

返回:

PS C:\Users\> C:\Users\somescript.ps1
C:\Users\somescript.ps1
C:\Users\somescript.ps1