Skip to content

Sorting Properties Of An Object

Tags: powershell


I had a CSV full of broken file paths and needed to get the longest path from each. When pulling in these paths we got objects like:

$tot[0]
count : 185
0 : CDRLs - DP BRIDGE N00421-15-C-0004
1 : A005 Vulner Assess
2 : 2015
3 : August
4 : Final
5 : Delivery Email_N0041-15-C-0004, CDRL A005 Application_Software Vulnerability Assessment (01 - 31 August 2015).pdf

I was not able to sort these in any way, I tried a basic way first:

Terminal window
foreach ($i in $tot[0].psobject.properties) {
$i.Value.Length | sort
}

In the Powershell discord I was told to try making it a process and that actually worked. I added the Selct statement to end up with the longest part of the path on each line.

Terminal window
$tot = Import-Csv total.csv
foreach ($one in $tot) {
& {
foreach ($i in $one.psobject.properties) {
$i.Value
}
} | Sort-Object -Property Length | Select -last 1
}

Sources:
  • https://stackoverflow.com/questions/23626308/powershell-array-get-the-longest-string,https://www.pwsh.ch/how-to-loop-through-the-properties-of-a-powershell-object-97.html,https://discord.com/channels/180528040881815552/446156137952182282/925075907113287771