VMware Cloud Community
DZ1
Hot Shot
Hot Shot
Jump to solution

PowerCLI to get VMs 3 at a time.

I'm working on a larger script, and I can't seem to wrap my head around it.  I want to get the names of some VMs, but I want to be able to get the VMs by groups of 3, it could be 2, or 4, I just arbitrarily chose 3.  My ultimate goal is to export the VMs, but I want to section them off, so I'm not running a large export at once.

So, if I have 12 VMs, I want to get the first 3, export them, and then the next 3, export them, and so on.

I realize that it may not always be 12, or some number that divides by 3, but I see that if I use Select-Object and select the -First 5 of something that has only 3, it seems to work without any error, so I'm not too concerned with making sure that the count is divisible by a certain number. 

I tried something like this:

#$MyCount was already populated with five VM names

$CountComplete = $null

$CountComplete = @()

While (($Mycount | sort)  -ne ($CountComplete | sort )) {

$MyCount |  select -First 3 | Get-Unique

$CountComplete += $Mycount

}

#$CountComplete += $Mycount

I know the above doesn't work, but I'm just wondering if that's the correct path?

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Try something like this

I placed some numbers in the array $test, but it could be VirtualMachine objects, the logic stays the same.

$test = 1,2,3,4,5,6,7,8,9,10

$start = 0

$step = 3

while($start -le $test.Count){

    Write-Output "Handling $($test[$start..($start + $step - 1)])"

    $start += $step

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

Reply
0 Kudos
2 Replies
LucD
Leadership
Leadership
Jump to solution

Try something like this

I placed some numbers in the array $test, but it could be VirtualMachine objects, the logic stays the same.

$test = 1,2,3,4,5,6,7,8,9,10

$start = 0

$step = 3

while($start -le $test.Count){

    Write-Output "Handling $($test[$start..($start + $step - 1)])"

    $start += $step

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
DZ1
Hot Shot
Hot Shot
Jump to solution

That is very nice, I modified what I needed, and it's running just as it should.  I made this change below

Get-VM ($mycount[$start..($start + $step - 1)])

It grabbed the first 3, and then I can pipe that to whatever command that I need to, and then of course it loops back around and gets the next 3, and so on.

I really appreciate your help, this is very useful.  As always, many many thanks.

Reply
0 Kudos