Forum Discussion
add computers to security group automatically
- Jan 21, 2021
did you add the * after the desktop1
try this small change
$AllPC=Get-ADComputer -Filter 'SamAccountName -like "desktop*"'
Use the following
(Get-ADComputer -Filter 'Name -like "Desktop*"' -properties displayname).foreach{add-adgroupmember -identity "MyADGROUP" -Members $_.SamAccountName}
Please remember that computer object should have at their end $, otherwise it will be considered as ad user account.
--------------
If you find this answer helpfull , Click on best response and give like
Hi, this is what i get:
Method invocation failed because [Microsoft.ActiveDirectory.Management.ADComputer] does not contain a method named 'foreac
h'.
At line:1 char:1
+ (Get-ADComputer -Filter 'Name -like "desktop1*"' -properties displayname ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (foreach:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Must there be a $ at desktop1$
- Surfer10Jan 21, 2021Copper Contributor
When i put $ ehind the computername the error does not appear but it does also not adding the computer to the security group, just tested with "desktop1$"
- Surfer10Jan 21, 2021Copper Contributor
When i do this:
Get-ADComputer -Filter 'Name -like "desktop1"' -properties displayname
The properties of the computer appears so thats okay.
- farismalaebJan 21, 2021Iron Contributor
it seems that you are using an old version of Powershell
Try this
$AllPC=Get-ADComputer -Filter 'Name -like "Desktop*"' -properties displayname foreach($SinglePC in $AllPC){ add-adgroupmember -identity "MyADGROUP" -Members $SinglePC.SamAccountName }