PowerShell Script to run commands per Active Directory OU

I regularly run into a case in which it is handy to have a script to hand to run against a group of windows desktops or servers in an Active Directory OU.

Requirements to run the below are below.

  1. WinRM needs to be running on the relevant desktops and servers (can be completed by GPO) or by running “winrm quickconfig” in a PowerShell session on the machine
  2. Remote Server Admin Tools need to be installed on the desktop or server in which you are running the script (not required on DC’s)

The script is broken down below.

Import the AD module (RSAT requirement)

The $OU variable holds the full LDAP filter of the targeted OU

The $Script variable holds the command to which you would want to run against the computers. (installations, batch scripts or any other commands)

The window title of the PowerShell windows will display “Processing Computers in OU OU=SETOFCOMPUTERS,OU=COMPUTEROU,DC=DOMAINNAME,DC=COM” while the Connectivity Timeout variable is used later to complete inital connectivity of the computer before completing the script.

The $ComputerNames variable uses the AD command Get-ADComputer with the filter of the $OU variable to select all computers in the targeted OU.

The foreach loop runs a test-connection or ping with a TTL of 20 seconds, if this fails the “Computer Not Found COMPUTERNAME” message will be returned. If successful then the invoke-command will run a remote PowerShell session to execute the $Script variable on the targeted desktop.


Full Code:


Leave a Reply

Your email address will not be published. Required fields are marked *