gpt4 book ai didi

powershell - 获取定义 PowerShell 函数的文件路径

转载 作者:行者123 更新时间:2023-12-04 13:08:27 25 4
gpt4 key购买 nike

我试图找出一种方法来获取定义 PowerShell 函数的文件路径(例如 Test1 或 Test2),而不是调用者的路径,这可以通过 $PSScriptRoot 轻松获得。自动变量。

考虑以下文件夹结构:

c:\Scripts\Test.ps1
c:\Scripts\Test1\Test1.ps1
c:\Scripts\Test2\Test2.ps1

测试.ps1
Set-Location $PSScriptRoot;
. .\Test1\Test1.ps1;
. .\Test2\Test2.ps1;

Test1;
Test2;

Test1.ps1
function Test1 {
[CmdletBinding()]
param (
)
Write-Host -Object "Entering Test1";
Write-Host -Object "Exiting Test1";
}

Test2.ps1
function Test2 {
[CmdletBinding()]
param (
)
Write-Host -Object "Test2";
Write-Host -Object "Exiting Test2";
}

我曾尝试在 $PSCmdlet 上使用各种属性和 $MyInvocation自动变量,但似乎无法找到一种方法来获取定义函数的文件的路径,而不是调用者所在的位置。

以不同的方式询问,我将如何获得路径 C:\Scripts\Test1\Test1.ps1从内部 Test1函数,当它从 Test.ps1 调用时? Test2.ps1 也是如此脚本和 Test2功能。我将如何获得路径 C:\Scripts\Test2\Test2.ps1从内部 Test2功能?

这是不可能的,因为我正在使用 .调用运算符,将函数导入当前 session ?

最佳答案

这是另一种方法,使用函数的 scriptblock File 属性获取包含该函数的文件:

${function:Test1}.File

关于powershell - 获取定义 PowerShell 函数的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com