none
Specifying more than one OU per function? RRS feed

  • Question

  • 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?

    Tuesday, March 20, 2018 3:48 PM

Answers

  • Put the distinguished names of the OUs you want into a list, and iterate the list.

    Example of how to create and iterate a list of items:


    $list = "A","B","C"
    
    $list | ForEach-Object {
      "Now processing $_"
    }
    


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by iTsLiKeAnEgG Tuesday, March 20, 2018 5:39 PM
    Tuesday, March 20, 2018 3:57 PM
    Moderator

All replies

  • Put the distinguished names of the OUs you want into a list, and iterate the list.

    Example of how to create and iterate a list of items:


    $list = "A","B","C"
    
    $list | ForEach-Object {
      "Now processing $_"
    }
    


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by iTsLiKeAnEgG Tuesday, March 20, 2018 5:39 PM
    Tuesday, March 20, 2018 3:57 PM
    Moderator
  • The -SearchBase parameter can only list one OU or container. So yes, you must repeat the code for each OU, in a loop as Bill suggests.

    But you can also specify the -SearchScope, so if you want to include one OU and all of the children of that OU, you can specify a scope of "subTree", which is also the default. To not include child OU's, specify scope "oneLevel".


    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Tuesday, March 20, 2018 4:04 PM
    Moderator
  • Good stuff guys! I was able to do this as such:

    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" $_
            }
        }
    }
    Tuesday, March 20, 2018 5:39 PM