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

问题描述 投票:10回答:6

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

模块:test.psm1

Function Get-Info {
    $MyInvocation.MyCommand.Name
}

脚本:myTest.ps1

Import-Module C:\Users\moomin\Documents\test.psm1 -force
Get-Info

当我运行./myTest.ps1时,我得到了

Get-Info

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

powershell powershell-v2.0
6个回答
12
投票

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

function Get-Info{
    $MyInvocation.PSCommandPath
}

示例myTest.ps1

Import-Module C:\Users\moomin\Documents\test.psm1 -force
Get-Info

输出:

C:\Users\moomin\Documents\myTest.ps1

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

GCI $MyInvocation.PSCommandPath | Select -Expand Name

那将输出:

myTest.ps1

7
投票

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

模块:test.psm1

Function Get-Info {
    $callstack = Get-PSCallStack
    $callstack[1].Location
}

输出:

myTest.ps1: Line 2

2
投票

使用$ 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;

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

Command : C:\Dev\Test-Script.ps1 - Path : C:\Dev\Test-Script.ps1
Command : Get-Invocation - Path : 

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

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


1
投票

要引用调用脚本的调用信息,请使用:

@(Get-PSCallStack)[1].InvocationInfo

e.f.:

@(Get-PSCallStack)[1].InvocationInfo.MyCommand.Name

0
投票

在尝试了几种技术后,我今天使用了它。

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$ScriptName = $MyInvocation.MyCommand | select -ExpandProperty Name
Invoke-Expression ". $Script\$ScriptName"

0
投票

这为脚本路径提供了尾部反斜杠作为一个变量,脚本名称作为另一个变量。

该路径适用于Powershell 2.0和3.0和4.0以及可能5.0的Posershell $ PSscriptroot现在可用。

$ _INST = $ myinvocation.mycommand.path.substring(0,($ myinvocation.mycommand.path.length - $ MyInvocation.mycommand.name.length))

$ _ScriptName = $ myinvocation.mycommand.path.substring($ MyInvocation.MyCommand.Definition.LastIndexOf('\'),($ MyInvocation.mycommand.name.length +1))

$ _ScriptName = $ _ScriptName.TrimStart('\')

© www.soinside.com 2019 - 2024. All rights reserved.