How to Loop through AD objects with PowerShell

While at work, I came across the problem of ‘You don’t own the network but you must deploy and administer the network’. That’s when I had the idea to employ PowerShell scripts and Batch files. When you are given tier 2 admin access to only a particular OU and not full admin access to the whole domain, these scripts might help you ensure your workstations stay up to date. How did I loop through AD objects with PowerShell?

Grab list from Active Directory

In order to loop through multiple active directory objects, I made the choice to grab all the objects in an OU and put them in a text file. To do this I ran a simple windows command in a batch file. Use the command ‘DSQUERY COMPUTER’.
For each OU, start at the top level OU and dive into the final OU.
For the Domain Controller (DC), start at your top level domain (example: blog) eventually diving into the overall domain (example: com, mil, org, us, etc…)

@echo off

DSQUERY COMPUTER "OU=TOPLEVEL,OU=MIDLEVEL,OU=LOWERLEVEL,OU=FINALLEVEL,DC=BLOG,DC=POWERSJO,DC=COM" -o rdn -limit 1000 > c:\objects.txt

pause

Using an array in PowerShell

$WorkstationArray =
''number1'', “number2”, “number3”

In the array put the list of objects from the batch file. I did this manually but I’m sure there is a way to automate it.

Loop through an array in PowerShell

for($i=0; $i -lt $WorkstationArray.Count; $i++){
$temp = $WorkstationArray[$i]
Write-Output "Initiate reboot for: " $temp
Restart-Computer -ComputerName $temp -Force
}

In the above loop I reference each workstation and initiate a restart of each one. If you use ‘-Force’, even when a user is logged in the workstation will restart.

In the next blog post I will post my method of running ‘gpupdate’, initiating RDP and running the PowerShell scripts as an administrator with batch files.

Enter your address to subscribe to this blog and receive notifications of new posts!

Published by Powersjo

If you want to contact me I can be found here: https://gab.com/Powersjo Christ is King