Welcome Forums General PowerShell Q&A Search AD folder & add computers to some groups

Viewing 2 reply threads
  • Author
    Posts
    • #168682
      Participant
      Topics: 5
      Replies: 6
      Points: 68
      Rank: Member

      Hi All

      I am writing a script to do the following

      search an ad folder & add any computer objects to some security groups

      Below is what I’ve pieced together,

      Import-Module ActiveDirectory
      $Computer = Get-ADComputer -Filter * -SearchBase "OU=folder"
      
      Do 
      {
      $ComputerCheckValid = Get-ADComputer $Computer -ErrorAction SilentlyContinue
      Sleep 10
      }
      While ($ComputerCheckValid -eq $null)
      
      Add-ADGroupMember "group" -Members "$Computer"
      Add-ADGroupMember "group2" -Members "$Computer"

      Now i know the get-adcomputer work individually, but not when combined as above. But i would like to use a for each, but unsure on how to go about it.

      Import-Module ActiveDirectory
      ForEach-Object {
      Get-ADComputer -Filter * -SearchBase "OU=folder"
      Add-ADGroupMember "Group" -Members "$_"
      }

      I thought that below would work, but get an error of cannot find object with identity: ‘ ‘ under: ‘DC=company’

       

      Would appreciate some help here.

       

    • #168880
      Participant
      Topics: 2
      Replies: 1761
      Points: 3,655
      Helping Hand
      Rank: Community Hero

      You don’t need to explicitly import modules anymore since Powershell version 3.0. The following should be enough:

      Get-ADComputer -Filter * -SearchBase "OU=folder" |
          ForEach-Object {
              Add-ADPrincipalGroupMembership -Identity $_.sAMAccountName -MemberOf 'group','group2'
          }
    • #168955
      Participant
      Topics: 5
      Replies: 6
      Points: 68
      Rank: Member

      Thank you, Works like a charm.

Viewing 2 reply threads
  • The topic ‘Search AD folder & add computers to some groups’ is closed to new replies.