6

I want to start a script1.ps1 out of an other script with arguments stored in a variable.

$para = "-Name name -GUI -desc ""this is the description"" -dryrun"
. .\script1.ps1 $para

The args I get in script1.ps1 looks like:

args[0]: -Name name -GUI -desc "this is the description" -dryrun

so this is not what I wanted to get. Has anyone a idea how to solve this problem?
thx lepi

PS: It is not sure how many arguments the variable will contain and how they are going to be ranked.

lepi
  • 83
  • 2
  • 4

2 Answers2

7

You need to use splatting operator. Look at powershell team blog or here at stackoverflow.com.

Here is an example:

@'
param(
  [string]$Name,
  [string]$Street,
  [string]$FavouriteColor
)
write-host name $name
write-host Street $Street
write-host FavouriteColor $FavouriteColor
'@ | Set-Content splatting.ps1

# you may pass an array (parameters are bound by position)
$x = 'my name','Corner'
.\splatting.ps1 @x

# or hashtable, basically the same as .\splatting -favouritecolor blue -name 'my name'
$x = @{FavouriteColor='blue'
  Name='my name'
}
.\splatting.ps1 @x

In your case you need to call it like this:

$para = @{Name='name'; GUI=$true; desc='this is the description'; dryrun=$true}
. .\script1.ps1 @para
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
stej
  • 28,745
  • 11
  • 71
  • 104
  • I'm glad I helped. If you are satisfied with the answer(s), you can close the questions by accepting the answer ;) – stej Aug 03 '10 at 13:24
  • Where the _splatting operator_? There's no operator here this just happens to be the way PowerShell processes the commands... i.e. it's a feature, not an operator. – John Leidegren Oct 01 '17 at 07:58
5

Using Invoke-Expression is another aternative:

$para = '-Name name -GUI -desc "this is the description" -dryrun'
Invoke-Expression -Command ".\script1.ps1 $para"
George Howarth
  • 2,767
  • 20
  • 18
  • thx, the result is at the end the same but this is the real nice and short variant! – lepi Aug 03 '10 at 11:32