PowerCLI

 View Only
  • 1.  Filtering an array based on hash table contents

    Posted Mar 29, 2014 01:28 AM

    I have a report that uses two arrays and a hashtable.

    1. $report = An array containing a group of VMs and custom properties for those VMs.  The virtual machine names are in a property called VMName

    2.  $removedvms = An array containing a list of virtual machine names.  The virtual machine names are also in a property called VMName

    3. $vmhash = A hash table

    For every virtual machine object that is present in the $report array and also has its name listed in the $removedvms array, I would like to remove the object from the $report array.  Using the code below, the hash table now has only the names of the VMs that are in $report but are NOT in $removedvms. 

    How do I remove the objects from $report that are NOT in $vmhash?

    $vmhash=@{}

    $report | %{$vmhash.Add($_.VMName,$_)}

    $removedvms | %{

    if($vmhash.ContainsKey($_.Name)){

    $vmhash.Remove($_.Name)

    }

    }



  • 2.  RE: Filtering an array based on hash table contents

    Posted Mar 29, 2014 08:07 AM

    You can remove the objects from $report that are not in $vmhash with:

    $report = $report | Where-Object {-not $vmhash[$_.VMName]}

    You don't have to use the hashtable, if you just create a list of the names of the removed vm's. For example:

    $RemovedVMNames = $removedvms | Select-Object -ExpandProperty VMName

    $report = $report | Where-Object {$RemovedVMNames -notcontains $_.VMName}



  • 3.  RE: Filtering an array based on hash table contents
    Best Answer

    Posted Mar 29, 2014 09:39 AM

    Try with

    $report = $report | where {!$vmhash.Contains($_.VMName)}