I want to pass all parameters from one powershell script to another script without knowing the named parameters. That other script is out of my control and I can not predict all the parameters it takes.
Example wrapper: wrapper.ps1
Set-StrictMode -v 2
$ErrorActionPreference="Stop"
write-host "ArgsIn:" $Args
$mypath= Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$Cmd, $NewArgs =$Args | foreach { $_ -replace "one",'two' }
$Cmd = $mypath+"\"+$Cmd
write-host "Running:" $Cmd $NewArgs
& $Cmd @NewArgs
exit $LastExitCode
Example called script: test.ps1)
Param(
[Parameter(Mandatory=$false)] [string]$BAR,
[Parameter(Mandatory=$false)] [string]$FOO
)
write-host "test: Args:" $Args
write-host "FOO" $FOO
write-host "BAR" $BAR
exit 0
If I call test.ps1 it works as expected:
PS C:\Test> .\test.ps1 -foo one -bar three
test: Args:
FOO one
BAR three
But if I try it via the wrapper, it maps the parameters positionally instead.
PS C:\Test> .\wrapper.ps1 test.ps1 -foo one
ArgsIn: test.ps1 -foo one
Running: C:\Test\test.ps1 -foo two
test: Args: test.ps1 -foo one
FOO two
BAR -foo
I have tried various alternative forms to call the script (including invoke-command and invoke-expression).
One way that appeared to work was using
invoke-expression "& `"$Cmd`" $NewArgs"
but that breaks as soon as any parameter contains a space:
PS C:\Test> .\wrapper.ps1 test.ps1 -foo "one three"
ArgsIn: test.ps1 -foo one three
Running: C:\Test\test.ps1 -foo two three
test: Args:
FOO two
BAR three
Is there any sensible way to do what I want?