$MyInvocation.MyCommand.Path returning NULL

Sea*_*ong 18 powershell

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

$ScriptPath = Split-Path $MyInvocation.MyCommand.Path
& $ScriptPath\build_functions.ps1
& $ScriptPath\build_builddefs.ps1
Run Code Online (Sandbox Code Playgroud)

我们的想法是获取正在运行的脚本的路径,并使用该路径调用一些支持脚本.但是,当我单独测试它以确保它可以工作时(通过突出显示该块并运行该代码),我收到以下错误:

Split-Path: Cannot bind argument to parameter 'Path' because it is null.
Run Code Online (Sandbox Code Playgroud)

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

CB.*_*CB. 24

$MyInvocation是一个在脚本运行时填充的自动变量,如果你在a中执行或者没有填充;$MyInvocation.MyCommand.Pathpowershell consoleISE

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

  • $ MyInvocation绝对是在ISE中填充的,但是当从本地函数内部调用时它没有完全填充,至少这是我测试中的快速假设.对于PowerShell 3.0+使用`$ PSCommandPath`和`$ PSScriptRoot` (2认同)