Search AD folder & add computers to some groups

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

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

 
Participant
1 month, 3 weeks ago.

  • 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: 1
    Replies: 1530
    Points: 2,591
    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.

You must be logged in to reply to this topic.