2
votes
# 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

The above script works great. I want now to use Start-Job to run it in the background, so I modified it to:

# 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

and I get this error:

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

How do I fix that?

2
Did you try passing the args as an array, like this -ArgumentList @($vmname, $vmtemplate.name)campbell.rw
@Paul That's clearly not possible.Ansgar Wiechers

2 Answers

5
votes

Check this, I know that you need change code a little bit :)

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

This is how you can pass a value inside Start-Job.

You have to invoke it from inside. This is my blog link for the same: 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