Specifying more than one OU per function?

Welcome Forums General PowerShell Q&A Specifying more than one OU per function?

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
7 months, 4 weeks ago.

  • Author
    Posts
  • #96534

    Participant
    Points: 1
    Rank: Member

    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?

  • #96537

    Participant
    Points: 134
    Helping Hand
    Rank: Participant

    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.

  • #96542

    Participant
    Points: 0
    Rank: Member

    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

    • #96555

      Participant
      Points: 1
      Rank: Member

      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" $_
              }
          }
      }
      

The topic ‘Specifying more than one OU per function?’ is closed to new replies.