A while back I posted an advanced PowerShell function that would take an object and convert it to a hashtable. The premise was simple enough: look at the incoming object with Get-Member to discover the property names then create a hashtable with each property name as a hashtable key. I’ve a need to use this over the last few weeks and realized the function could use a little updating.
The new version works like the old, with the addition of one new parameter. I decided I wanted a way to exclude properties from the hashtable. Of course this presumes you know in advance about the object you are working with and what properties you wish to exclude. This is the core segment of code, which has also been revised over version 1.
#go through the list of names and add each property and value to the hash table
$names|ForEach-Object{
#only add properties that haven't been excluded
if($Exclude-notcontains$_){
#only add if -NoEmpty is not called and property has a value
if($NoEmpty-AND-Not($inputobject.$_)){
Write-Verbose'Skipping $_ as empty'
}
else{
Write-Verbose'Adding property $_'
$hash.Add($_,$inputobject.$_)
}
}#if exclude notcontains
else{
Write-Verbose'Excluding $_'
}
}#foreach
$names|ForEach-Object{
#only add properties that haven't been excluded
if($Exclude-notcontains$_){
#only add if -NoEmpty is not called and property has a value
if($NoEmpty-AND-Not($inputobject.$_)){
Write-Verbose'Skipping $_ as empty'
}
else{
Write-Verbose'Adding property $_'
$hash.Add($_,$inputobject.$_)
}
}#if exclude notcontains
else{
Write-Verbose'Excluding $_'
}
}#foreach
A while back I posted an advanced PowerShell function that would take an object and convert it to a hashtable. The premise was simple enough: look at the incoming object with Get-Member to discover the property names then create a hashtable with each property name as a hashtable key.
![Array Array](https://evotec.xyz/wp-content/uploads/2019/02/img_5c6b366847fbd.png)
In the first version I was duplicating some code and I generally try to avoid that. In this snippet $names is the collection of property names and $Inputobject is the piped in object. Armed with this tool I can create hashtables from objects with just the properties I want.
PS Scripts:![Convert Convert](https://msdnshared.blob.core.windows.net/media/2018/03/HashTable-Keys-Output.jpg)
PS Scripts:> $h
Name Value
---- -----
ServiceName spooler
ServiceType Win32OwnProcess, InteractiveProcess
Name spooler
DisplayName Print Spooler
MachineName .
Status Running
ServiceHandle SafeServiceHandle
DependentServices {Fax}
RequiredServices {http, RPCSS}
ServicesDependedOn {http, RPCSS}
---- -----
ServiceName spooler
ServiceType Win32OwnProcess, InteractiveProcess
Name spooler
DisplayName Print Spooler
MachineName .
Status Running
ServiceHandle SafeServiceHandle
DependentServices {Fax}
RequiredServices {http, RPCSS}
ServicesDependedOn {http, RPCSS}
This version should work in PowerShell 2.0 or 3.0. Download ConvertTo-Hashtable2.