Search AD folder & add computers to some groups

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"

$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.


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’

Thank you, Works like a charm.