如何从Powershell模块返回调用脚本的名称?

Mar*_*son 10 powershell powershell-2.0

我有两个Powershell文件,一个模块和一个调用模块的脚本.

模块:test.psm1

Function Get-Info {
    $MyInvocation.MyCommand.Name
}
Run Code Online (Sandbox Code Playgroud)

脚本:myTest.ps1

Import-Module C:\Users\moomin\Documents\test.psm1 -force
Get-Info
Run Code Online (Sandbox Code Playgroud)

当我跑步时,./myTest.ps1我得到了

Get-Info

我想返回调用脚本的名称(test.ps1).我怎样才能做到这一点?

The*_*ian 12

在您的模块中使用PSCommandPath:
示例test.psm1

function Get-Info{
    $MyInvocation.PSCommandPath
}
Run Code Online (Sandbox Code Playgroud)

示例myTest.ps1

Import-Module C:\Users\moomin\Documents\test.psm1 -force
Get-Info
Run Code Online (Sandbox Code Playgroud)

输出:

C:\Users\moomin\Documents\myTest.ps1
Run Code Online (Sandbox Code Playgroud)

如果您只想要可以通过执行来管理的脚本的名称

GCI $MyInvocation.PSCommandPath | Select -Expand Name
Run Code Online (Sandbox Code Playgroud)

那将输出:

myTest.ps1
Run Code Online (Sandbox Code Playgroud)


Jam*_*mes 7

我相信你可以使用Get-PSCallStack cmdlet,它返回一个堆栈帧对象数组.您可以使用它来识别调用脚本到代码行.

模块:test.psm1

Function Get-Info {
    $callstack = Get-PSCallStack
    $callstack[1].Location
}
Run Code Online (Sandbox Code Playgroud)

输出:

myTest.ps1: Line 2
Run Code Online (Sandbox Code Playgroud)


Har*_* F. 5

使用 $MyInvocation.MyCommand 是相对于它的范围。

一个简单的例子(位于:C:\Dev\Test-Script.ps1 的脚本):

$name = $MyInvocation.MyCommand.Name;
$path = $MyInvocation.MyCommand.Path;

function Get-Invocation(){
   $path = $MyInvocation.MyCommand.Path;
   $cmd = $MyInvocation.MyCommand.Name; 
   write-host "Command : $cmd - Path : $path";
}

write-host "Command : $cmd - Path : $path";
Get-Invocation;
Run Code Online (Sandbox Code Playgroud)

运行 .\c:\Dev\Test-Script.ps1 时的输出:

Command : C:\Dev\Test-Script.ps1 - Path : C:\Dev\Test-Script.ps1
Command : Get-Invocation - Path : 
Run Code Online (Sandbox Code Playgroud)

如您所见,$MyInvocation 是相对于范围的。如果您想要脚本的路径,请不要将其包含在函数中。如果您想要调用该命令,则将其包装起来。

您也可以按照建议使用调用堆栈,但要注意范围规则。