Author Posts

March 20, 2018 at 3:24 pm

Hi All,

I have a powershell script that remotely executes a batch script to reboot workstations and prompts the user to cancel if they need. I would like to know if I can efficiently list multiple OU's without having to repeat the execution for each OU? The following executes on the "Accounting" OU:

Import-Module ActiveDirectory

$Exclude = Get-ADGroupMember RES_RebootExclusionTest | Select -Exp Name

Get-ADComputer -SearchBase 'OU=Accounting,DC=abc,DC=xyz,DC=com' -Filter '*' | Select -Exp Name |
 ForEach-Object{
 	if($Exclude -notcontains $_){
        	Start-Process "WeekendReboot.bat" $_
        }
    }

What if I also want to execute on the Finance, Sales, etc OU's? Do I have to list multiple identical blocks within the powershell script for each OU?

March 20, 2018 at 3:31 pm

Do I have to list multiple identical blocks within the powershell script for each OU?

No. We don't do that in Powershell. 😉 Either you start your AD search more in the root of the OU tree and filter the computer for the given OUs. But that's a bad idea because it's not efficient. Or you create a loop and place you code inside the loop for each single OU you have in an array.

March 20, 2018 at 3:45 pm

You can also have a text file with all OUs you need:
OU=Accounting,DC=abc,DC=xyz,DC=com
OU=Sales,DC=abc,DC=xyz,DC=com

and then do like this:

$file = Get-Content 'ou.txt'
foreach ($ou in $file) {
 Get-ADComputer -SearchBase $ou -Filter '*'
}

This at least allows you to separate data from business logic

March 20, 2018 at 5:40 pm

This is a good option. I ended up doing the following but may switch to a file:

Import-Module ActiveDirectory

$Exclude = Get-ADGroupMember RES_RebootExclusionTest | Select -Exp Name
$OU = "OU=Reboot Test1,OU=Workstations,OU=Test,DC=abc,DC=xyz,DC=com","OU=Reboot Test2,OU=Workstations,OU=Test,DC=abc,DC=xyz,DC=com"


$OU | ForEach{
Get-ADComputer -SearchBase $_ -Filter '*' | Select -Exp Name |
 ForEach-Object{
 	if($Exclude -notcontains $_){
        	Start-Process "WeekendReboot.bat" $_
        }
    }
}