Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top