Convert Object Properties Into HashTable


Views

Everything is an object in PowerShell, and every object has it’s own properties, methods and some objects have events as well. Especially when it is working with the object properties, we can’t run through each property by its name & value in a loop, so to work with the individual properties we can convert the object properties into a HashTable and with the .GetEnumerator() and then you can manage the properties individually.

The script below to convert the object properties into HashTable…

# Converts Object properties to HashTable.
Function Convert-ObjectToHashTable
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [pscustomobject] $Object
    )
    $HashTable = @{}
    $ObjectMembers = Get-Member -InputObject $Object -MemberType *Property
    foreach ($Member in $ObjectMembers) 
    {
        $HashTable.$($Member.Name) = $Object.$($Member.Name)
    }
    return $HashTable
}

Example output:


Share it on     |   |   |   | 
  Prev:  

Know Your Azure VM Created Date Using PowerShell & AZCli

  :Next  

Variable Squeezing in PowerShell

comments powered by Disqus