I would like To store a variable in a config file for a .ps1(powershell script) converted to .exe using ps2exe
$LnkPath="...\" #Directory Path of .lnk
$LnkFile="\nnnn.lnk" #name of .lnk file
Invoke-Item $ScriptPath $LnkFile
I was hoping to have $LnkFile
and $LnkPath
as config file variables so if the version of the lnk stops working, i can just point to a new lnk.
There is a reason why the version of the .lnk file stops working, but it is complicated, and not worth anyone's time.
CodePudding user response:
The config file created with the optional -configFile
switch isn't meant for use by the wrapped script - it merely contains runtime metadata for the generated executable (in the form of an XML file placed alongside the executable with additional extension .config
).
However, you can create your own config file.
While PowerShell has a configuration-data format that uses hashtable-literal syntax, which can be read with Import-PowerShellDataFile
, as of PowerShell 7.2.x there is no way to create this format programmatically.
A simple alternative that supports both reading and programmatic creation is to use a JSON file:
The following assumes that your script file is foo.ps1
, to be converted to foo.exe
, with a configuration file foo.json
located in the same directory (which you'll have to bundle with your .exe
file when deploying it):
First, create your JSON config file:
@{ LnkPath = '...\'; LnkFile = 'nnnn.lnk' } | ConvertTo-Json > foo.json
Now you can read this file from foo.ps1
/ foo.exe
as follows:
# Determine this script's / executable's full path.
$scriptOrExePath =
if ($PSCommandPath) { # Running as .ps1
$PSCommandPath
} else { # Running as .exe"
Convert-Path ([Environment]::GetCommandLineArgs()[0])
}
# Look for the JSON config file in the same directory as this script / executable, load it and parse it into an object.
$config =
Get-Content -Raw ([IO.Path]::ChangeExtension($scriptOrExePath, '.json')) |
ConvertFrom-Json
# $config is now an object with .LnkPath and .LnkFile properties.
$config # Output for diagnostic purposes.
Note the need to use [Environment]::GetCommandLineArgs()
to determine the executable path when running as an .exe
file, because the usual automatic variables indicating the script path ($PSCommandPath
) and script directory ($PSScriptRoot
) aren't available then.