Search code examples
arrayspowershellstart-job

PowerShell - Passing expanded arguments to Start-Job cmdlet


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!


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