Convert object in PowerShell (for example [PsCustomObject]) into hash table source code


I needed a simple and reusable PowerShell code to convert any object into hash table that can be copy and pasted as source code. I wrote this:

$outputItem = '@{'

$MyCustomObject.PSObject.Properties.Name |
    Where-Object -FilterScript { $_ -ne 'ComputerName' } | ForEach-Object -Process `
    {
        if ($interfaceItemIpConfigurationItem.$_ -is [bool])
        {
            $valueItem = '${0}' -f $MyCustomObject.$_.ToString().ToLower()
        }
        else
        {
            $valueItem = "'{0}'" -f ($MyCustomObject.$_ -join "', '")
        }

        $outputItem += "`r`n{0} = {1}" -f $_.Padright(16, ' '), $valueItem
    }

$outputItem += "`r`n}"

# Output
$outputItem

Leave a Reply

Your email address will not be published. Required fields are marked *

Active Directory Advanced function AlwaysOn Availability Groups AlwaysOn Failover Cluster Instances Building Cloud Cloud Cluster Cmdlet Database Deployment Design DFS Domain Controller DSC Fabric Failover Clustering File Server Group Policy Hardware Profile Host Hyper-V Installation Library Library Asset Library Server Network Operations Manager Orchestrator PowerShell PowerShell User Group PowerShell Workflow Security Service Manager SQL Server Storage System Center Template Time Time Synchronization Tips Virtual Machine Virtual Machine Manager VM Network VM Template Windows Server 2012 R2