3

We're trying to create an array with variables and then pass this array as expanded to a script, which shall be run by Start-Job. But actually it fails and we are unable to find the reason. Maybe someone can help!?

$arguments= @()
$arguments+= ("-Name", '$config.Name')
$arguments+= ("-Account", '$config.Account')
$arguments+= ("-Location", '$config.Location')

#do some nasty things with $config

Start-Job -ScriptBlock ([scriptblock]::create("& .'$ScriptPath' [string]$arguments")) -Name "Test"

It fails with

Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
    + CategoryInfo          : InvalidData: (:) [Select-AzureSubscription], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.WindowsAzure.Commands.Profile.SelectAzureSubscriptionCommand
    + PSComputerName        : localhost

Even though $config.name is set correctly.

Any ideas?

Thank you in advance!

2 Answers2

5

I use this method for passing named parameters:

$arguments = 
@{
   Name     = $config.Name
   Account  = $config.Account
   Location = $config.Location
}

#do some nasty things with $config

Start-Job -ScriptBlock ([scriptblock]::create("&'$ScriptPath'  $(&{$args}@arguments)")) -Name "Test"

It lets you use the same parameter hash you'd use to splat to the script if you were running it locally.

This bit of code:

$(&{$args}@arguments)

embedded in the expandable string will create the Parameter: Value pairs for the arguments:

$config = @{Name='configName';Account='confgAccount';Location='configLocation'}
$arguments = 
@{
   Name     = $config.Name
   Account  = $config.Account
   Location = $config.Location
}

"$(&{$args}@arguments)"

-Account: confgAccount -Name: configName -Location: configLocation
mjolinor
  • 66,130
  • 7
  • 114
  • 135
2

The single quote is the literal string symbol, you are setting the "-Name" argument to the string $config.Name not Value of $config.Name. To use the value, use the following:

$arguments= @()
$arguments+= ("-Name", $config.Name)
$arguments+= ("-Account", $config.Account)
$arguments+= ("-Location", $config.Location)
Eris
  • 7,378
  • 1
  • 30
  • 45
  • Hi Eris! The single quote is not used by accident. If you do a invoke-impression an that argument, it will expand the strings. We wanted to keep this behaviour, but it doesn't seem to work though. Maybe someone has an idea on this!? Best regards! – user3812803 Jul 30 '14 at 12:10