
close
close
Recently, a follower sent me an email with a problem that he was trying to solve with Active Directory (AD) and PowerShell. At first, I was a little puzzled by what he was trying to do. We spent some time going back and forth on possible solutions. During the process, I realized his situation presented a great teachable opportunity. Let’s see what we can learn about PowerShell.
The initial problem was to find all AD computer accounts, where part of the name was found in a list of names. The initial code, which was not working, looked something like this:
$Filter = (Get-Content names.txt) Get-AdComputer -Filter * | where-object{"*"+$_.name+"*" -match $Filter} | select name
It did not have errors but it also did not have results. Let me show you what is in the names.txt file.
Get-AdComputer -Filter * | where-object{ $filter -contains $_.name} | select name
This does not quite work. If by chance $Filter contained the complete name, then this approach would work.
advertisment
“Get the computer names from AD and then look at each name. If the computer name property matches a value from the list of names, then get the computer name and distinguished name properties.”
At this point, it also became clear that trying to write this as a one-line solution was not practical. It could probably be done but it would be overly complicated. This is a trap many PowerShell beginners fall into, thinking they need to write one-line solutions. This not true. Sometimes, it makes much more sense to break the process down into several steps.
Based on my narrative, I knew the first step was to get all the computer accounts from AD.
$ad = Get-ADComputer -filter *
This turned out to be 96 items in my test domain. Next, get the list of usernames from the text file.
$names = Get-content .\names.txt
The main comparison has to be done on each computer account, one at a time. To make it easy to follow, I used the ForEach enumerator.
advertisment
foreach ($name in $names) { $ad | Where {$_.name -match $name} | Select name,distinguishedname }
The code loops through each name. It then pipes $ad to Where-Object to see if the name matches.
$ad = Get-ADComputer -filter {Name -notlike "CHI-*"}
Now, I get 44 computer names. Here is my revised ForEach loop with a better regular expression pattern and using the Where() method for better performance.
foreach ($name in $names) { ($ad).Where({$_.name -match "$name$"}) | Select name,distinguishedname }
There are certainly other ways to solve this problem but I hope you will pay attention to the process and principals I used.
More in PowerShell
Microsoft’s New PowerShell Crescendo Tool Facilitates Native Command-Line Wraps
Mar 21, 2022 | Rabia Noureen
Most popular on petri