PowerShell - 当嵌套在点源CA中时,如何获取调用Class的脚本文件的名称

发布于 2020-03-27 10:30:58

如果我有以下内容(简化的安装程序)

class.ps1

class Test {
    Test() {
        $MyInvocation | Show-Object
    }

    [void] Call() {
        $MyInvocation | Show-Object
        <# 
           here $MyInvocation.ScriptName, PSCommandPath show main.ps1 NOT 
           util.ps1 even though it is called from Util.ps1 
        #>
    }
}

实用程序

Write-Host "Calling from Util.ps1"
$MyInvocation | Show-Object

Function Test-Util {
    [CmdletBinding()]
    Param()

    Write-Host "Calling from Test-Util in Util.ps1"
    $MyInvocation | Show-Object
}

Function Test-Class {
    [CmdletBinding()]
    Param()

    write-host "Testing Class Test from Util.ps1"
    $Test = [Test]::new()
    Write-Host "Testing Class.Call() from Util.ps1"
    $Test.Call()
}

Function Test-SubUtilTest {
    [CmdletBinding()]
    Param()

    Test-SubUtil
}

SubUtil.ps1

Write-Host "Calling from SubUtil.ps1"
$MyInvocation | Show-Object

Function Test-SubUtil {
    [CmdletBinding()]
    Param()

    Write-Host "Calling from Test-Util in Util.ps1"
    $MyInvocation | Show-Object 

    <# 
        here $MyInvocation.ScriptName, PSCommandPath show Util.ps1 NOT 
        main.ps1 as it is called from Util.ps1 
    #>
}

Main.ps1

. C:\Users\jenny\Class.ps1
. C:\Users\jenny\Util.ps1
. C:\Users\jenny\SubUtil.ps1

Write-Host "From Main.ps1"
$MyInvocation | Show-Object

write-host "Calling Test-Util from util.ps1"
Test-Util

Write-Host "Calling Test-Class from util.ps1"
Test-Class

write-host "Calling Test-SubUtil from Util.ps1"
Test-SubUtilTest

$ Test = [Test] :: new()

$ Test.Call()

都是从util.ps1执行的

但是$ MyInvocation仅向我显示main.ps1

我如何从类的构造方法或其方法之一确定其调用代码所源自的ps1文件(在此类嵌套点源设置中)

我试过交换为&而不是。而且我还尝试过将class.ps1的点源移到util.ps1文件中,但它仍然告诉我main.ps1是源。

再加上真实的类文件是一个单例文件,可以在多个点源util.ps1文件中使用,我不确定是否可以在每个点都源于main.ps1的多个文件中点源同一个类文件(不是那个在此示例中,将点源移动到单个实用程序文件中有所不同)

最后,我使用PowerShellCookbook模块中的Show-Object。

它对于基于函数的嵌套调用有效,但不适用于对类的调用,这似乎很奇怪

查看更多

查看更多

提问者
TofuBug
被浏览
86
mhu 2019-07-03 22:43

您可以使用堆栈来确定调用方:

class Test {
    Test() {
        Get-PSCallStack | Select-Object -First 1 -Skip 1 -ExpandProperty "Location" | Write-Host
    }

    [void] Call() {
        Get-PSCallStack | Select-Object -First 1 -Skip 1 -ExpandProperty "Location" | Write-Host
    }
}

发布
问题

分享
好友

手机
浏览

扫码手机浏览