CodeSOD: An Odd Sort
Let's say we wanted to query Active Directory and print out a report of all of our users, and their last logon time. That seems like a pretty normal task for a Powershell script. It'd probably be short and easy to read, at least if it were written by a normal person.
Alice sends us one that wasn't. She's already done us a favor, as she writes: "Code cleaned up and indented for the whitespace-missing-impaired."
##################################### # lists accounts and selected attributes alphabetically ##################################### foreach( $letter in "a", "b", "c"......"z") { $strfilter = $letter + "*" $objdomain = New-object System.DirectoryServices.DirectoryEntry $objSearcher = New-object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = $objdomain $objSearcher.Filter = $strFilter $objSearcher.PropertiesToLoad.Add("name"); $colResults = $objSearcher.FindAll() foreach($result in $colResults) { $name = $result.Properties.Name $searcher = New-Object DirectoryServices.DirectorySearcher([adsi]"") $searcher.filter "(&(objectCategory=User)(sAMAccountName=$name))" $users = searcher.FindAll() foreach($user in $users) { Write-Output $user.properties.item("name") + "," + $user.properties.item("lastLogon") } } }This accomplishes sorting alphabetically by iterating across the alphabet. Which, I suspect, isn't going to actually get them in alphabetical order; it makes sure that albert and alice appear before bob, but doesn't enforce that albert must come before alice.
In any case, we iterate across the alphabet, and then create a searcher that finds a*, then b*, etc. We explicitly tell the searcher that the only property we care about is the name field, so that we don't load unnecessary fields, like the ones we want to report on.
We then iterate across the list of names, construct a new searcher, and search for the account with the username we fetched. That lets us get all of the fields we need, including the ones we aren't going to use.
Now, we search for a username, so we expect there to only be one result, but since searcher.FindAll() returns an array, we "need" to write a loop to iterate across the array of one, which is clearly a better choice than using the FindOne function.
As it usually goes with these sorts of things, one of the managers absolutely adores the fact that they have an easy way to generate a CSV file that they can manipulate in Excel, so this terrible script is "mission critical".
.comment {border: none;} [Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.Surge in first-time buyers taking on higher levels of mortgage debt to get on housing ladder
Delays and cancellations amid Greater Anglia disruption at Colchester station
Shailene Woodley leads Emmys 2026 worst dressed list in bizarre mismatched look
'Aaron Rodgers is vindicated': Fans mock Shailene Woodley with ex's comments over BIZARRE Emmys outfit
ER reunion! Noah Wyle is cheered on by Julianna Margulies as he takes home Lead Actor in a Drama AGAIN for The Pitt at 2026 Emmys
Channel 4 documentary on future of the Royal Family claims one in four Brits now want to abolish the monarchy
Jamie Lee Curtis delivers emotional memorial to late friends Rob and Michele Reiner at 2026 Emmys
Piddington fightback against migrant camps 'could spread across the whole country' - as Reform and Tories back villagers' 'referendum' on leaving UK
Best cheap cars for students: Nine used motors for less than £3,000 to take to university
Smeg has finally launched an air fryer - but would you really spend £199.95 on one? Charlotte Vossen shares her verdict
How can I ensure my wife provides for my son as well as my stepson equally if I die first?
'Mouldy' chopping board found at 1-rated Essex Subway branch
Apple iPhone Duo makes developers think in folds
Emmy fans left stunned over Sheryl Lee Ralph's age as actress wows in glamorous gown on red carpet
Newlyweds Zendaya and Tom Holland look loved-up as they flash their wedding rings at Emmys 2026 after surprise nuptials
Jon Hamm, 55, proudly poses with pregnant wife Anna Osceola, 38, as expectant parents take to Emmys 2026 red carpet
Mariska Hargitay, 62, twins with daughter, 15, as Emmys 2026 host poses with husband Peter Hermann and kids on rare red carpet
Prince Archie and Princess Lilibet 'removed from school' by Duke and Duchess of Sussex after just two days of term - due to security fears
ChatGPT-Using Lawyer Cited Its Fake Witnesses and Police Testimony in Court
Read more of this story at Slashdot.