Hey everyone! I'm working on a PowerShell snippet where I'm trying to extract certain fields from a collection of hashtables. I have the following code that populates an array with information:
```
$out = foreach ($prc in $prcs){
@{
Name = $prc.Name
Handles = $prc.Handles
Time = Get-Date -Format FileDateTimeUniversal
}
}
```
So here's my issue: when I try to select only the 'Name', 'Handles', and 'Time' fields in PowerShell version 5.1, it doesn't return anything. However, in version 7.5, it returns the expected data formatted as a table.
I'd like to get the same result in version 5.1 as clean as possible, preferably in a one-liner. Is there a way I can use `$out.GetEnumerator()` to achieve this? Thanks for your help!
4 Answers
If you aren’t dependent on those intermediate hashtables, try this instead:
```
$prcs | Select-Object -Property Name, Handles, @{ N = 'Time'; E = { Get-Date -Format FileDateTimeUniversal } }
```
It's really straightforward!
You can modify your original code a bit by replacing `@{` with `[pscustomobject]@{`. This way, you’ll convert the hashtables into PowerShell custom objects, which should work much better!
Exactly! Just that small change makes all the difference.
Keep in mind though, if you have larger functions returning data, you might need to manipulate the `$out` you're using.
You can convert an array of hashtables to custom objects this way:
```
$out | ForEach-Object { [pscustomobject]$_ } | Select-Object Name, Handles
```
It keeps everything neat and tidy!
Not sure I fully understand your output goal, but if this helps, you can also do:
```
$out = $prcs |
Select-Object -Property Name, Handles, @{n='Time';e={Get-Date -Format FileDateTimeUniversal}}
```
That should yield what you need!

Thanks for that! It’s much cleaner than my initial approach.