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

时间:2018-11-03 18:44:38

标签: powershell

我创建了ps1脚本,并使用此命令动态获取路径

$ScriptPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

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

$ScriptPath = Split-Path -Parent $PSCommandPath

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

1 个答案:

答案 0 :(得分:3)

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

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 = "." } 
}