Powershell $MyInvocation.MyCommand.Path returns null when convert script in exe

Viewed 2041

I created my ps1 script and to get the path dynamically I used this command

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

Everything works fine when I use ISE console but when I try to convert my ps1 script to exe with ps2exe, I get an error when I execute my exe file because $ScriptPath returns null value.
I tried this way but without success

$ScriptPath = Split-Path -Parent $PSCommandPath

I would like the script to be compatible with version 2.
How could I solve it?
Thank you

1 Answers

You can obtain the path with following script:

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