While an executable compiled with ps2exe uses a .ps1
file as input, at runtime no actual .ps1
file is involved, which is why PowerShell's command-reflection variables cannot tell you anything about a running script file.
When running an actual .ps1
file, you'd use the following about_Automatic_Variables:
$PSCommandPath
contains the the executing script file's full file path.
$PSScriptRoot
contains the script file's full directory path (i.e. the full path of the directory in which the script file is located).
In a ps2exe-compiled executable (.exe
), where these variables have no values, you can use the following instead:
[Environment]::GetCommandLineArgs()[0]
contains the executable file's full file path.
Split-Path -LiteralPath ([Environment]::GetCommandLineArgs()[0])
contains the executable file's full directory path.
Applied to your code - assuming that a separate StartApp.ps1
file is present alongside your .exe
file:[1]
$FileLocale = Split-Path -LiteralPath ([Environment]::GetCommandLineArgs()[0])
$AntFile = Join-Path $FileLocale StartApps.ps1
If you want to make your code work in both invocation scenarios - the original .ps1
file directly as well as the compiled .exe
file - use the following:
$FileLocale =
if ($PSScriptRoot) { $PSScriptRoot }
else { Split-Path -LiteralPath ([Environment]::GetCommandLineArgs()[0]) }
$AntFile = Join-Path $FileLocale StartApps.ps1
[1] Note that at runtime no information is available about where the original .ps1
file that served as compile-time input was originally located - only that file's content becomes part of the .exe
file.