PowerShell - 将扩展参数传递给 Start-Job cmdlet

use*_*803 3 arrays powershell start-job

我们尝试创建一个包含变量的数组,然后将该数组作为扩展传递给脚本,该脚本将由 Start-Job 运行。但实际上却失败了,我们也找不到原因。也许有人可以帮忙!?

$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"
Run Code Online (Sandbox Code Playgroud)

它失败了

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
Run Code Online (Sandbox Code Playgroud)

即使 $config.name 设置正确。

有任何想法吗?

先感谢您!

mjo*_*nor 5

我使用此方法来传递命名参数:

$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"
Run Code Online (Sandbox Code Playgroud)

如果您在本地运行脚本,它允许您使用与用于 splat 的相同参数哈希。

这段代码:

$(&{$args}@arguments)
Run Code Online (Sandbox Code Playgroud)

嵌入可扩展字符串将为参数创建参数:值对:

$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
Run Code Online (Sandbox Code Playgroud)