How to Select Data from Hashtables in PowerShell 5.1?

0
12
Asked By CodingNinja88 On

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

Answered By PowerShellPro77 On

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!

CraftyCoder01 -

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

Answered By TechWizard42 On

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!

ScriptingGuru23 -

Exactly! Just that small change makes all the difference.

DevDude99 -

Keep in mind though, if you have larger functions returning data, you might need to manipulate the `$out` you're using.

Answered By HashTableHero On

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!

Answered By QueryMaster34 On

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!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.