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!
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.
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.
Thanks a lot, Matt!
It's exactly what I need!