Search code examples
powershellvirtual-machinereplicationpowershell-3.0windows-server-2012-r2

How do I create a custom array in powershell?


I am trying to sort out arrays in PS. The problem I am trying to solve is to return a list of replicated VMs and some basic stats.

Having read through a multitude of sites and suggestions the best I could get is the following script:

$myArray = @()

$vms = get-vm | where-object { $_.replicationstate -ne "Disabled" }

foreach ($vm in $vms)
{
    $vmRepl = Get-VMReplication

    $replfreq = (New-TimeSpan -seconds $vmRepl.replicationfrequencysec)
    $lastrepl = $vmRepl.lastreplicationtime
    $nextrepl = $lastrepl + $replfreq
    $secfrom = [math]::Round((New-TimeSpan -start     $vmRepl.lastreplicationtime).TotalSeconds)
    $secto = [math]::Round((New-TimeSpan -end ($vmRepl.lastreplicationtime + $replfreq)).TotalSeconds)

    $obj = New-Object System.Object
    $obj | Add-Member -MemberType NoteProperty -Name Name -Value $vmRepl.Name
    $obj | Add-Member -MemberType NoteProperty -Name ReplicationFrequencySec -Value $vmRepl.replicationfrequencysec
    $obj | Add-Member -MemberType NoteProperty -Name SecondsSinceLastRepl -Value $secfrom
    $obj | Add-Member -MemberType NoteProperty -Name SecondsUntilNextRepl -Value $secto
    $obj | Add-Member -MemberType NoteProperty -Name LastReplication -Value $lastrepl
    $obj | Add-Member -MemberType NoteProperty -Name NextReplication -Value $nextrepl

    $myArray += $obj

}

write-output $myArray | ft -AutoSize

This works when I only have one VM, but when there are multiple ones the output appears within curly braces.

I think I am on the right track finally. I just need someone to help me sort out the remaining piece(s) of the puzzle.

The other weird thing is that the New-TimeSpan stops working with multiple VMs.

Thanks in advance.

Braden


Solution

  • The biggest probem with your script is : you start a foreach loop but you don't use any element from the array you're looping through. You just loop through the same data for each item in the array.

    Basicly the current script retreives a list of VMs, then for each entry you fetch the replication status of all the machines in the array. Then you do some processing on this set and then add this set to a new object (and this goes on for each entry in your list). For a good explanation on the usage of foreach see http://blogs.technet.com/b/heyscriptingguy/archive/2014/04/28/basics-of-powershell-looping-foreach.aspx

    I would also suggest to use [PSCustomObject] instead of new-object / add-member : it's easier to use, the code is easier to read and it also maintains the order of the properties you set with it (since you're using get-vm I assume you have PS3 or higher)