<# ----------------------------------------------------------------------------- Script: ConvertTo-Hashtable.ps1 Version: 1.0 Author: Jeffery Hicks http://jdhitsolutions.com/blog http://twitter.com/JeffHicks http://www.ScriptingGeek.com Date: 10/21/2011 Keywords: Comments: Convert an object to a hash table. Use -NoEmpty to not export properties with no values "Those who forget to script are doomed to repeat their work." **************************************************************** * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED * * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF * * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, * * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. * **************************************************************** ----------------------------------------------------------------------------- #> Function ConvertTo-HashTable { [cmdletbinding()] Param( [Parameter(Position=0,Mandatory=$True,HelpMessage="Please specify an object", ValueFromPipeline=$True)] [object]$InputObject, [switch]$NoEmpty ) Process { Write-Verbose "Converting an object of type $($_.GetType().Name)" #get propery names $names=$InputObject | get-member -MemberType properties | select-object -expandproperty name #define an empty hash table $hash=@{} #go through the list of names and add each property and value to the hash table $names | foreach-object { Write-Verbose "Adding property $_" $hash.Add($_,$inputobject.$_) } #foreach if ($noEmpty) { Write-Verbose "Parsing out empty values" #define a new hash $defined=@{} #get items from $hash that have values and add to $defined $hash.keys | foreach-object { if ($hash.item($_)) { $defined.add($_,$hash.item($_)) } } Write-Verbose "Writing the result to the pipeline" Write-Output $defined } else { Write-Verbose "Writing the result to the pipeline" Write-Output $hash } #If $noempty }#close process }#end function