Skip Ribbon Commands
Skip to main content

Quick Launch

Todd Klindt's home page > Todd Klindt's Office 365 Admin Blog > Posts > Sorting Hash Tables in PowerShell
March 23
Sorting Hash Tables in PowerShell

I recently was working on a customer project and I was trying to find the name of a certain SharePoint list item property. (Spoiler, it was “_ModerationStatus”) I knew it was hiding in the item’s FieldValues property, but I wasn’t sure where. To get you up to speed, here’s the PowerShell that got me to this spot:

Connect-PnPOnline -Url https://m365x246038.sharepoint.com/sites/ContosoWeb1
(Get-PnPListItem -List "SitePages" -Id 5).FieldValues

SNAGHTML155621a

Not only is the list of FieldValues as long as my kids’ Christmas Lists, also like those lists, it’s not in alphabetical, chronological, numerical, or any other order I can conjure up. To say it’s random seems to be giving it more order than it really has.

While I didn’t know exactly was the name of the property I did have a few ideas. Trying to find those random property names would make swimming upstream look like a piece of cake. Fortunately I’ve fought this battle before and I have the scars to prove it. I’m hoping I can save you all the pain I went through, over and over.

The secret is the GetEnumerator() Method of the Hash Table. This got me what I was looking for:

(Get-PnPListItem -List "SitePages" -Id 5).FieldValues.GetEnumerator() | Sort-Object -Property Key

SNAGHTML17b6b87

Isn’t that much better?

Once you introduce .GetEnumerator() into the picture you can also get crazy with things like Where-Object, like this:

(Get-PnPListItem -List "SitePages" -Id 5).FieldValues.GetEnumerator() | Sort-Object -Property Key  | Where-Object -Property Key -Like -Value "*mod*"

or

(Get-PnPListItem -List "SitePages" -Id 5).FieldValues.GetEnumerator() | Sort-Object -Property Key  | Where-Object -Property Value -Like -Value "true"

SNAGHTML1825780

Normally you would put the Where-Object before the Sort-Object so that the Sort has fewer items to churn through.

While I did this in the context of a hash of SharePoint list item properties, it’s applicable to all PowerShell hash tables.

Happy PowerShelling.

tk

ShortURL: https://www.toddklindt.com/PoshSortHashTables

Comments

There are no comments for this post.

Add Comment

Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Title


Body *


Today's date *

Select a date from the calendar.
Please enter today's date so I know you are a real person

Twitter


Want a message when I reply to your comment? Put your Twitter handle here.

Attachments

 

 SysKit