如何将变量传递给 Start-Job?

Pau*_*aul 2 variables parameters powershell

# Select Template and add ID for easy selection
$templates = Get-Folder Templates01 |
             Get-Template |
             Select name |
             % {$counter = -1} {
               $counter++;
               $_ | Add-Member -Name Template_ID -Value $counter -MemberType NoteProperty -PassThru
             }

$templates | ft -Auto
$MyTemplate = Read-Host "select VM Template_ID"
$VMTemplate = $templates[$MyTemplate]

$VMNAME = Read-Host "Specify VM Name"

New-Vm -Name $VMNAME -Template $vmtemplate.Name
Run Code Online (Sandbox Code Playgroud)

上面的脚本效果很好。我现在想用来Start-Job在后台运行它,所以我把它修改为:

# Select Template and add ID for easy selection
$templates = Get-Folder Templates01 |
             Get-Template |
             Select name |
             % {$counter = -1} {
               $counter++;
               $_ | Add-Member -Name Template_ID -Value $counter -MemberType NoteProperty -PassThru
             }

$templates | ft -Auto
$MyTemplate = Read-Host "select VM Template_ID"
$VMTemplate = $templates[$MyTemplate]

$VMNAME = Read-Host "Specify VM Name"

$scriptblock = {
  Param( $1, $2 )
  New-Vm -Name $1 -Template $2 
}

Start-Job -ScriptBlock $scriptblock -ArgumentList $vmname $vmtemplate.Name
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

开始作业:无法绑定参数“InitializationScript”。不能
将“System.String”类型的“template01”值转换为类型
“系统.管理.自动化.ScriptBlock”。
在行:1 字符:59
+ ... -Job -ScriptBlock $scriptblock -ArgumentList $vmname $vmtemplate.Name
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidArgument: (:) [Start-Job], ParameterBindingException
    +FullyQualifiedErrorId:CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.StartJobCommand

我该如何解决?

小智 5

检查这个,我知道你需要稍微更改代码:)

Start-Job -ScriptBlock {Get-ChildItem  $args[0],$args[1] } -ArgumentList $a,$b
Run Code Online (Sandbox Code Playgroud)