我们尝试创建一个包含变量的数组,然后将该数组作为扩展传递给脚本,该脚本将由 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"

它失败了

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

即使 $config.name 设置正确。

有任何想法吗?

先感谢您!

有帮助吗?

解决方案

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

$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"
.

它允许您使用相同的参数散列,如果您在本地运行它,则使用它用于SPLAT到脚本。

该代码:

$(&{$args}@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
.

其他提示

单引号是文字字符串符号,您将“-Name”参数设置为字符串 $config.Name 不是 Value of $config.Name. 。要使用该值,请使用以下命令:

$arguments= @()
$arguments+= ("-Name", $config.Name)
$arguments+= ("-Account", $config.Account)
$arguments+= ("-Location", $config.Location)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top