Forum Discussion

Surfer10's avatar
Surfer10
Copper Contributor
Jan 21, 2021
Solved

add computers to security group automatically

I would like to add computers in AD with names that start with desktop to a security group: testgroup.

We would like to run this powershell command thru scheduled tasks to run every week so that if someone forgets to add the computer to the security group it will be done. Every computer with name desktop must be aded to that group.

 

I have the following:

Get-ADComputer -Filter 'Name -like "desktop*"' -properties displayname | add-adgroupmember -identity "testgroup"

 

When i run this it asks for a members(0)

 

How can we accomplish this?

 

 

 

 

I would like to first test it with desktop1 in stead of *.

  • Surfer10 

    did you add the * after the desktop1

    try this small change

    $AllPC=Get-ADComputer -Filter 'SamAccountName -like "desktop*"'

12 Replies

  • Giancarlo135's avatar
    Giancarlo135
    Copper Contributor
    ADD-ADGroupMember -identity “NAME OF YOUR GROUP” –members “$env:computername$”

    Comments:
    The "" can be taken literally
    “$env:computername$” = this is a variable that will add the Computer that the script is running on to your specified Group
  • farismalaeb's avatar
    farismalaeb
    Iron Contributor

    Surfer10 

    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

     

    • Surfer10's avatar
      Surfer10
      Copper Contributor

      farismalaeb 

       

      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$

      • Surfer10's avatar
        Surfer10
        Copper Contributor

        Surfer10 

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

Resources