Powershell $MyInvocation.MyCommand.Path 在 exe 中转换脚本时返回 null

Gus*_*Gus 3 powershell

我创建了我的 ps1 脚本并动态获取路径我使用了这个命令

$ScriptPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
Run Code Online (Sandbox Code Playgroud)

当我使用 ISE 控制台时一切正常,但是当我尝试使用 ps2exe 将我的 ps1 脚本转换为 exe 时,当我执行我的 exe 文件时出现错误,因为 $ScriptPath 返回空值。
我试过这种方式但没有成功

$ScriptPath = Split-Path -Parent $PSCommandPath
Run Code Online (Sandbox Code Playgroud)

我希望脚本与版本 2 兼容。
我该如何解决?
谢谢

Pet*_*der 5

您可以使用以下脚本获取路径:

if ($MyInvocation.MyCommand.CommandType -eq "ExternalScript")
{ 
   $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition 
}
else
{ 
   $ScriptPath = Split-Path -Parent -Path ([Environment]::GetCommandLineArgs()[0]) 
   if (!$ScriptPath){ $ScriptPath = "." } 
}
Run Code Online (Sandbox Code Playgroud)