powershell - 如何确定执行函数的文件名

标签 powershell

我正在运行一些代码并尝试记录特定的事情。在日志中,我想记录当前函数和该函数所在的文件名。

例如,我的“Main.ps1”文件类似于以下内容:

. .\UtilityFunctions.ps1

function Main-Routine
{
    utility-method
}

Main-Routine

我的 UtilityFunctions.ps1 类似于以下内容:
function utility-method
{
    "{0}.{1}" -f $MyInvocation.ScriptName, $MyInvocation.MyCommand
}

这将打印到控制台,如下所示:

mypath\Main.ps1.utility-method

我希望它改为打印:

mypath\UtilityFunctions.ps1.utility-method

似乎调用 $MyInvocation 总是返回在启动时调用的文件名,而不是函数所在的文件名。如何获取包含我的函数的文件名?

最佳答案

我相信您要查找的内容存储在 Get-Command 返回的对象中

(Get-Command Utility-Method).ScriptBlock.File

它应该既适用于点源脚本中定义的函数,也适用于模块中的函数。

关于powershell - 如何确定执行函数的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39646517/

相关文章:

regex - Powershell替换中可能存在错误,还是我做错了?

PowerShell 函数参数

json - 如何使用powershell按键对对象进行排序

python - 在 powershell、python 或其他运行 windows 的脚本语言中通过首字母移动文件

javascript - Powershell 选择 ID 元素并从网页中单击

python - 有没有一种直接的方法可以在 Windows 上获得完整的工作 Python 环境?

用于设置 pagefile.sys 大小的 PowerShell 脚本

powershell - 创建一个功能以遍历Powershell

powershell - 在 Powershell 中,获取连接路径以使用 $null 和空字符串

powershell - 使用 PowerShell 制作驱动器的 VHD 镜像