Alex Pratt
Alex Pratt

Reputation: 48

Passing in Parameters With -ArgumentList and Start-Job not Working. What's wrong with the code?

I'm currently having a problem with trying to multi-thread the deployment of virtual machines (VMWare specifically) and I'm using the following code to attempt that:

connect-viserver vcenter

for($i=251; $i -le 261; $i++) {

Start-Job {Param([string]$num) New-vm -ResourcePool Storage-POCs -Name "virtual-machine-$num" -vm "newvm" -Datastore MyDataStore} -ArgumentList $i

}

Here is the output I'm currently getting in terminal from this code:

HasMoreData   : True
StatusMessage :
Location      : localhost
Command       : Param([string]$num)
            New-vm -ResourcePool Storage-POCs -Name "virtual-machine-$num" -vm "newvm" -Datastore MyDataStore
JobStateInfo  : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : 3a6b8f27-c8d8-4386-9e58-6c1dfcfef52c
Id            : 419
Name          : Job419
ChildJobs     : {Job420}
Output        : {}
Error         : {}
Progress      : {}
Verbose       : {}
Debug         : {}
Warning       : {}
State         : Running


HasMoreData   : True
StatusMessage :
Location      : localhost
Command       : Param([string]$num)
            New-vm -ResourcePool Storage-POCs -Name "virtual-machine-$num" -vm "newvm" -Datastore MyDataStore
JobStateInfo  : Running
...

Can anyone tell me why the $num isn't translating into a number which would be $i?

Thanks, Alex

Upvotes: 0

Views: 1952

Answers (1)

FoxDeploy
FoxDeploy

Reputation: 13537

So, the command is actually executing as you would expect, it's just that when you run Get-Job, it is showing you the precise command executed. Meaning that it shows us $num as the name of the string, rather than the value.

The substitution doesn't actually happen until the command is executed.

You can test by just dumping the values into a text file, like this.

for($i=251; $i -le 261; $i++) {

Start-Job {Param([string]$num) "virtual-machine-$num">>t:\test.txt} -ArgumentList $i

}

Now, when I run Get-Job | select -expand Command, I'll still see:

Param([string]$num) "virtual-machine-$num">>t:\test.txt
Param([string]$num) "virtual-machine-$num">>t:\test.txt
Param([string]$num) "virtual-machine-$num">>t:\test.txt
Param([string]$num) "virtual-machine-$num">>t:\test.txt
Param([string]$num) "virtual-machine-$num">>t:\test.txt
Param([string]$num) "virtual-machine-$num">>t:\test.txt

However, when I read the file, I see that it actually did what I wanted:

virtual-machine-251
virtual-machine-252
virtual-machine-253
virtual-machine-254
virtual-machine-255
virtual-machine-256
virtual-machine-257
virtual-machine-258
virtual-machine-259
virtual-machine-260
virtual-machine-261

So, essentially this was actually working, it just didn't look like it was.

Upvotes: 1

Related Questions