I'm looking for a way from within a powershell script to run a second powershell script, where the parameters are stored in a string variable. Here is a - very simplified - example:
. $path\MainScript.ps1 -Mode $($objBMA.{Mode}) -InstallPath ${Env:ProgramFiles(x86)}
Like this everything works fine. But apparently you can't simply replace the parameter string "-Mode Install -InstallPath ${Env:ProgramFiles(x86)}" with a variable, like
$parameters = '-Mode Install -InstallPath ${Env:ProgramFiles(x86)}'
. $path\MainScript.ps1 $parameters
In this case, there's no variable expansion and parameter binding doesn't work as it should, meaning that the parameter "Mode" is not "Install" but "-Mode Install -InstallPath ${Env:ProgramFiles(x86)}".
Tested with the following script "MainScript.ps1":
param(
[string]$Mode,
[string]$InstallPath
)
"="*120
"Bound parameters passed to 'MainScript.ps1':"
$PSBoundParameters
"="*120
"Unbound parameters passed to 'MainScript.ps1':"
$args
"="*120
Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<MainScriptName>MainScript.ps1</MainScriptName>
<MainScriptParameters>-Mode $($objBMA.{Mode}) -InstallPath ${Env:ProgramFiles(x86)}</MainScriptParameters>
I tried "Invoke-Expression" (e.g. Invoke-Expression -Command 'Write-Output "$parameters"'), only to run into new problems - and also this command is said to be "dangerous"!? I suppose there must be a better solution!?
Background: I'm working on a helper script for software distribution, which automatically runs the main script with logging (Start-Transcription), error handling, and so on. The parameters for the main script are read from a config file.