powershell - $MyInvocation.MyCommand.Path 返回 NULL

标签 powershell

我有以下代码作为较长脚本的开头:

$ScriptPath = Split-Path $MyInvocation.MyCommand.Path
& $ScriptPath\build_functions.ps1
& $ScriptPath\build_builddefs.ps1

这个想法是获取正在运行的脚本的路径并使用该路径调用一些支持脚本。但是,当我单独测试它以确保它可以工作时(通过突出显示该块并仅运行该代码),我收到以下错误:
Split-Path: Cannot bind argument to parameter 'Path' because it is null.

有趣的是,当我运行整个脚本时,它似乎分别运行这些文件。关于 ISE 如何处理运行选择而不是完整脚本,我是否遗漏了什么?运行选择时它不会建立文件系统上下文吗?

最佳答案

$MyInvocationautomatic variable居住在 脚本运行时间 , 那么如果你执行 $MyInvocation.MyCommand.Pathpowershell consoleISE没有人口;

这就是为什么在您的测试中 $ScriptPath没有值(value) ( $null )

关于powershell - $MyInvocation.MyCommand.Path 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18742354/

相关文章:

powershell - 我的 PowerShell 脚本在从批处理文件或命令行打开时不起作用,但在直接运行时起作用

regex - 从字符串中提取键值

powershell - 尝试使用 Powershell 安装 Sysinternals 时的警告

powershell - 使用 Powershell 从一个文件夹中的多个 CSV 文件中删除前 15 行

powershell - 如何为服务启动时间查询选择正确的输出格式?

powershell - 如何比较文件中的两个顺序字符串

sql - 如何自动启动 SQL Server 代理作业

powershell - 为什么我需要先在 PowerShell 脚本中编写函数?

windows - 如何访问位于 Windows 上具有保留系统名称(如 "CON")的文件夹中的本地文件?

powershell - Powershell搜索和替换中的编码问题