首页 文章

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

提问于
浏览
0
# 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

上面的脚本效果很好 . 我现在想使用 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

我收到此错误:

Start-Job : Cannot bind parameter 'InitializationScript'. Cannot
convert the "template01" value of type "System.String" to type
"System.Management.Automation.ScriptBlock".
At line:1 char:59
+ ... -Job -ScriptBlock $scriptblock -ArgumentList $vmname $vmtemplate.Name
+                                                          ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Start-Job], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.StartJobCommand

我该如何解决这个问题?

2 回答

  • 3

    检查一下,我知道你需要更改代码:)

    Start-Job -ScriptBlock {Get-ChildItem  $args[0],$args[1] } -ArgumentList $a,$b
    
  • 0

    这是您在Start-Job中传递值的方法 .

    你必须从里面调用它 . 这是我的博客链接:Start-Job Passing value

    $ini='$var="'+$args[0]+'"'
    $a={
     Function Get-add()
            {
            "this  is the value of $var"
    
            }
     }
    start-job -InitializationScript $a -ScriptBlock {param($ini)iex $ini;get-add } -ArgumentList $ini |Wait-Job | Receive-Job
    

相关问题