PowerShell - 传递扩展参数给Start-Job命令

3
我们正在尝试创建一个包含变量的数组,并将该数组扩展后传递给脚本,然后通过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被正确设置,还有什么想法吗?
提前感谢您!
2个回答

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"

如果您在本地运行脚本,它会让您使用与散开相同的参数哈希。

以下代码片段:

$(&{$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

嗨,mjolinor!你的解决方案起了作用。非常感谢你! - user3812803
有人知道如何在 $arguments 上添加一个 [System.Management.Automation.PSCredential] 属性吗? - xavier

2
单引号是字面字符串符号,您正在将“-Name”参数设置为字符串$config.Name而不是$config.Name的值。要使用该值,请使用以下内容:
$arguments= @()
$arguments+= ("-Name", $config.Name)
$arguments+= ("-Account", $config.Account)
$arguments+= ("-Location", $config.Location)

嗨Eris! 单引号的使用并非偶然。如果你在调用invoke-impression时传入该参数,它将会展开字符串。我们希望保持这种行为,但似乎并没有起作用。也许有人对此有什么想法? 最好的问候! - user3812803

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接