VMware Cloud Community
qwert1235
Enthusiast
Enthusiast
Jump to solution

How add object to the array

Hello:

I have general question about powerCLI: how can I create array and add object to this array later?

Basically, I am selecting all VMs, checking something on them by using "foreach" and "if" later some condition matches with what I need I want to put it (vm) to the specific array ($vms) that I will use later.

How can I do it?

Thanks a lot!

0 Kudos
1 Solution

Accepted Solutions
mattboren
Expert
Expert
Jump to solution

Hello, qwert1235-

You can use something like the following:

## initialize a new array
$arrVMs = @()
Get-VM | %{
   
## if the VM is config'd with more than 4GB mem, add it to the array
    if ($_.MemoryMB -gt 4096) {$arrVMs += $_}
}
## end foreach-object

But, really, you should be able to avoid the extra code and just make an array of the items that you want from the start, like:

## make an array of VMs config'd w/ more than 4GB mem
$arrVMs = Get-VM | ?{$_.MemoryMB -gt 4096}

There are times, though, when adding to an array would be necessary.  The first example would do just that.

View solution in original post

0 Kudos
2 Replies
mattboren
Expert
Expert
Jump to solution

Hello, qwert1235-

You can use something like the following:

## initialize a new array
$arrVMs = @()
Get-VM | %{
   
## if the VM is config'd with more than 4GB mem, add it to the array
    if ($_.MemoryMB -gt 4096) {$arrVMs += $_}
}
## end foreach-object

But, really, you should be able to avoid the extra code and just make an array of the items that you want from the start, like:

## make an array of VMs config'd w/ more than 4GB mem
$arrVMs = Get-VM | ?{$_.MemoryMB -gt 4096}

There are times, though, when adding to an array would be necessary.  The first example would do just that.

0 Kudos
qwert1235
Enthusiast
Enthusiast
Jump to solution

Thanks a lot, Matt!

It's exactly what I need!

0 Kudos