none
Powershell one-liner to add domain user to a local group

    Question

  • I'm looking for a one liner that can be typed in to add a domain user to a local group.  I know it can be done using net.exe but with the trend to move admin controls to powershell I doubt net.exe will be around much longer.  (It has issues with multiple domains anyway.)

    So I'm looking for a powershell equivalent to this:

       net localgroup administrators /add DomainA\User1

    v3 for Win8/2012 is fine, this is for new stuff.

    I've seen a 2004 blog post for a script to do this but I'm looking for a oneliner about the size of the net command.

    Thanks!

    Friday, September 21, 2012 8:32 PM

Answers

  • I don't think you're going to be fortunate to get that short of a command for local groups in PowerShell, but I could be wrong.  Technically speaking there is nothing "wrong" with running "net localgroup administrators /add DomainA\User1" from within PowerShell.  You could get fancier and literally pass that command to Invoke-Expression, but I get that's not what you are after.

    A little newer Hey, Scripting Guy! Blog post might be what you are after Use PowerShell to Add Domain Users to a Local Group

    However, he only gets it down to 2 lines of code:

    $de = [ADSI]"WinNT://$computer/$Group,group" 
    $de.psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)

    Someone might be able to wrap that into a single line, but that might be as short as it gets in this case right now.

    • Marked as answer by StefMahoney Tuesday, September 25, 2012 9:40 PM
    Friday, September 21, 2012 9:12 PM

All replies

  • I don't think you're going to be fortunate to get that short of a command for local groups in PowerShell, but I could be wrong.  Technically speaking there is nothing "wrong" with running "net localgroup administrators /add DomainA\User1" from within PowerShell.  You could get fancier and literally pass that command to Invoke-Expression, but I get that's not what you are after.

    A little newer Hey, Scripting Guy! Blog post might be what you are after Use PowerShell to Add Domain Users to a Local Group

    However, he only gets it down to 2 lines of code:

    $de = [ADSI]"WinNT://$computer/$Group,group" 
    $de.psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)

    Someone might be able to wrap that into a single line, but that might be as short as it gets in this case right now.

    • Marked as answer by StefMahoney Tuesday, September 25, 2012 9:40 PM
    Friday, September 21, 2012 9:12 PM
  • There's another post by Ed here.

    I wouldn't be concerned with one liners. This can easily be made into a function so you can call it by a simple one liner.

    example:

    Add-UserToLocalGroup -User barnesa -LocalGroup Administrators



    Blog: http://scriptimus.wordpress.com

    Friday, September 21, 2012 9:41 PM
    Moderator
  • To add to Andrew's excellent post I suggest looking in the repository as there are numerous scripts there that will do this.

    http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx

    And I and lobbying for users to look first into the repository because you will find much to use and will like what you find.  Forgive me for my crassness but I failed "Marketing 101".  It put me to sleep.


    ¯\_(ツ)_/¯


    • Edited by jrv Saturday, September 22, 2012 4:42 PM
    Friday, September 21, 2012 10:51 PM
  • Andrew, where can I find this function Add-UserToLocalGroup ? I need some module-import?

    http://www.petri.co.il/managing-local-user-accounts-with-powershell.htm

    http://gallery.technet.microsoft.com/Local-Account-Management-a777191b


    Gastone Canali >http://www.armadillo.it

    Se alcuni post rispondono al tuo quesito (non necessariamente i miei), ricorda di contrassegnarli come risposta e non dimenticare di contrassegnare anche i post utili . GRAZIE!


    • Edited by GastoneCanali Saturday, September 22, 2012 4:20 PM
    • Proposed as answer by Speedbird85 Thursday, August 28, 2014 5:52 PM
    Saturday, September 22, 2012 4:16 PM
  • What Andrew meant was that you could wrap this code in a function:

    $de = [ADSI]"WinNT://$computer/$Group,group"
    $de
    .psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)

    You would need to pass it at least three parameters: Computer, Group, and User.  The domain could be hard-coded.


    Grant Ward, a.k.a. Bigteddy

    Sunday, September 23, 2012 7:34 AM
  • I need to read with more attention...  "This can easily be made into a function "

    Gastone Canali >http://www.armadillo.it

    Se alcuni post rispondono al tuo quesito (non necessariamente i miei), ricorda di contrassegnarli come risposta e non dimenticare di contrassegnare anche i post utili . GRAZIE!

    Sunday, September 23, 2012 11:39 AM
  • Cheers all:

    A one liner to the rescue:

    # use one line to add a user to a local group
    ([ADSI]"WinNT://$computer/$Group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)
    #
    #

    Of course we can cheet a bit and write function all in one line(it is not really a one-liner;) )

    # a function all on one line
    function Add-LocalUser{Param($computer=$env:computername,$group='Guests',$userdomain=$userdomain,$useraccount=$username)([ADSI]"WinNT://$computer/$Group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)}
    #
    #
    #


    Of course making this readable is always preferred.

    function Add-LocalUser{
         Param(
            $computer=$env:computername,
            $group='Guests',
            $userdomain=$env:userdomain,
            $username=$env:username
        )
            ([ADSI]"WinNT://$computer/$Group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)
    }

    It is also really easy now to add help.  Just add one single line and you will get:
         help Add-LocalUser
         Add-LocalUser -?
         -debug
         -verbose,
         -erroraction,
         -errorvriable,
         -warningaction,
         -warningvariable,
         -outvariable,
         -outbuffer

    And much much more.

    All this for one very simple line of code added to a function. (?one line?)


    ¯\_(ツ)_/¯





    • Edited by jrv Sunday, September 23, 2012 4:55 PM
    • Proposed as answer by Al Dunbar Tuesday, September 25, 2012 10:55 PM
    Sunday, September 23, 2012 4:50 PM
  • Nicely done, JRV. Coming up with one-liner solutions is a bit of a challenge, however, using them is even more of a challenge, and ususally more work, more typing, and more chance of error than embedding the code in a function that *is* easier to invoke with a one-liner command.


    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    Sunday, September 23, 2012 5:17 PM
  • Al - yes - One-liners are nice at the console, I use them all of the time.  When one-liners are too complicated they can be couterproductive and, as you noted, prone to errors that are difficult to analyse.


    ¯\_(ツ)_/¯

    Sunday, September 23, 2012 5:58 PM
  • Thanks guys.

    This is for a server just a few seconds after it has an IP address, so I don't have the option of using prebuilt code since everything has to be new off the disc.  Sounds like something for MS to consider including in their commandlets.

    Thanks!

    Tuesday, September 25, 2012 9:42 PM
  • I don't think you're going to be fortunate to get that short of a command for local groups in PowerShell, but I could be wrong.  Technically speaking there is nothing "wrong" with running "net localgroup administrators /add DomainA\User1" from within PowerShell.  You could get fancier and literally pass that command to Invoke-Expression, but I get that's not what you are after.

    A little newer Hey, Scripting Guy! Blog post might be what you are after Use PowerShell to Add Domain Users to a Local Group

    However, he only gets it down to 2 lines of code:

    $de = [ADSI]"WinNT://$computer/$Group,group" 
    $de.psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)

    Someone might be able to wrap that into a single line, but that might be as short as it gets in this case right now.


    Nice two-liner. See jrv's onel-liner version.

    Al Dunbar -- remember to 'mark or propose as answer' or 'vote as helpful' as appropriate.

    Wednesday, September 26, 2012 4:12 AM
  • I wrote mine like this, Just fill in your info and remove mine from the variables at the top..

    It can be put into one line but I spread it out for easy reading and I am putting in about 40 of these in a row to add the same SQL Repl User into multiple SQL Security Groups.  Works like a charm! 

    Thanks

    WarParty

    # use one line to add a user to a local group
    $Computer = 'ExpressScriptsSQL33'

    $Group = 'VHAWarSQLP'

    $Domain = 'FQDN.WarParty.Com'

    $User = 'DIT_SQLReplSvc'

    ([ADSI]"WinNT://$computer/$Group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)
    #

    Wednesday, May 7, 2014 2:27 PM
  • could someone be so kind and add a loop to reference a machine.txt?
    Thursday, July 17, 2014 2:49 PM
  • could someone be so kind and add a loop to reference a machine.txt?

    No.  This thread is closed and answered.


    ¯\_(ツ)_/¯

    Thursday, July 17, 2014 2:52 PM
  • Function add-Localuser { [cmdletbinding()] Param ( $Computer = '', $Group = 'Administrators', $Domain = 'SomeDomain.org', $User = 'SomeUserID') ( [ADSI]"WinNT://$computer/$Group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path) }

    #use one of these methods to get server names...Comment/uncomment whichever

    #is preferred. Also make sure to pass/hard set the domain/user/group.

    $machines = Get-Content C:\temp\MyServers.txt $machines = "MyServer0","MyServer1","MyServer2","MyServer3" foreach ($m in $machines) { add-Localuser -computer $m } # you can also change the "Add" in the function to "Remove" or add a

    # parameter to pass it as a value.

    Thursday, February 5, 2015 11:49 AM
  • A little late reply, I know.  You could wrap this into an invoke-command.

    invoke-command -computername $computer -scriptblock {net localgroup administrators /add DomainA\User1}

    Kind of cheating, but gets the job done in one line :)

    Monday, August 10, 2015 11:11 PM
  • Thank you, this worked for me!  My problem was I kept getting the following error when trying to add an AD group to a remote machine using PS:

    Exception calling "Add" with "1" argument(s): "A member could not be added to or removed from the local group because the member does not exist.

    I used what you have above and rather than hard coding the domain and Group into the path (like I was doing), I used variables which fixed my issue.

    $ComputerName = Read-Host "Computer name:"
    $Group = 'Administrators'
    $domain = 'myCompanyDomainWithoutABackSlash'
    $user = 'ADgroupIWantToAdd'
    ([ADSI]"WinNT://$ComputerName/$Group,group").psbase.Invoke("Add",([ADSI]"WinNT://$domain/$user").path)

    Monday, September 21, 2015 2:54 PM
  • I know this is reviving an old thread but it comes up high on search engines and I wanted to share the latest update!

    With PowerShell 5+ (possibly 4, but unsure when exactly these cmdlets were released):

    Add-LocalGroupMember -Group Administrators -Member DOMAIN\UserOrGroupName

    You can also do this with batches of computers at a time using the Invoke-Command cmdlet

    Invoke-Command -ComputerName HOSTNAME1,HOSTNAME2,HOSTNAME3 -ScriptBlock { Add-LocalGroupMember -Group Administrators -Member DOMAIN\UserOrGroupName }


    There's your one liner!  Thank you PowerShell team for including this!

    Saturday, December 10, 2016 3:56 AM
  • PS 5 and later only.


    \_(ツ)_/

    Saturday, December 10, 2016 4:37 AM
  • I know this is reviving an old thread but it comes up high on search engines and I wanted to share the latest update!

    With PowerShell 5+ (possibly 4, but unsure when exactly these cmdlets were released):

    Add-LocalGroupMember -Group Administrators -Member DOMAIN\UserOrGroupName

    You can also do this with batches of computers at a time using the Invoke-Command cmdlet

    Invoke-Command -ComputerName HOSTNAME1,HOSTNAME2,HOSTNAME3 -ScriptBlock { Add-LocalGroupMember -Group Administrators -Member DOMAIN\UserOrGroupName }


    There's your one liner!  Thank you PowerShell team for including this!

    Anyone have the code that could be put into a previous version of a powershell script, so that the Add-LocalGroupMember function works?

    Wednesday, February 15, 2017 1:40 AM
  • Please don't piggyback on 5 year ols closed topics.  If you have a question open a topic under your name with a clear explanation of what you have tried and any complete error messages.


    \_(ツ)_/

    Wednesday, February 15, 2017 2:30 AM
  • This will allow you to remove or add an AD user to local group.

    #box to input the required domain
    $domain = read-host "Type User Domain"
    #box to enter the user ID
    $U = read-host "Type Username"
    #box to enter device name or IP
    $M = read-host "Type the computer name or IP"
    #box to add group name
    ########################

    # Edit This item to change the DropDown Values

    [array]$DropDownArray = "Administrators", "Power Users", "Remote Desktop Users", "Users"

    # This Function Returns the Selected Value and Closes the Form

    function Return-DropDown {
     $script:Choice = $DropDown.SelectedItem.ToString()
     $Form.Close()
    }

    function selectShare{
        [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
        [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")


        $Form = New-Object System.Windows.Forms.Form

        $Form.width = 300
        $Form.height = 150
        $Form.Text = ”DropDown”

        $DropDown = new-object System.Windows.Forms.ComboBox
        $DropDown.Location = new-object System.Drawing.Size(100,10)
        $DropDown.Size = new-object System.Drawing.Size(130,30)

        ForEach ($Item in $DropDownArray) {
         [void] $DropDown.Items.Add($Item)
        }

        $Form.Controls.Add($DropDown)

        $DropDownLabel = new-object System.Windows.Forms.Label
        $DropDownLabel.Location = new-object System.Drawing.Size(10,10) 
        $DropDownLabel.size = new-object System.Drawing.Size(100,40) 
        $DropDownLabel.Text = "Select Local Group"
        $Form.Controls.Add($DropDownLabel)

        $Button = new-object System.Windows.Forms.Button
        $Button.Location = new-object System.Drawing.Size(100,50)
        $Button.Size = new-object System.Drawing.Size(100,20)
        $Button.Text = "Select an Item"
        $Button.Add_Click({Return-DropDown})
        $form.Controls.Add($Button)

        $Form.Add_Shown({$Form.Activate()})
        [void] $Form.ShowDialog()


        return $script:choice
    }
    $G = selectShare
    $A = read-host "type add or remove"
    #SET command line to variables
    $Group = ([ADSI]"WinNT://$m/$G,group")
    $User = ("WinNT://$domain/$u,user")
    #the next line runs it all
    If ($a -eq "add") {powershell -c ($Group).add($user)}
    If ($a -eq "remove") {powershell -c ($Group).remove($user)}
    Else {write-host "Parameter entered incorrectly"}

    • Proposed as answer by Chris Rardin Thursday, June 15, 2017 6:35 PM
    • Edited by Chris Rardin Thursday, June 15, 2017 6:38 PM Comment
    Thursday, June 15, 2017 6:33 PM
  • Since this thread is already a shit show, I figured I would chime in with my $0.02:

    Add-LocalGroupMember -Group "Administrators" -Member "Some User"

    This is a built-in command, and, it just works. :)



    Friday, June 30, 2017 9:57 PM
  • Since this thread is already a shit show, I figured I would chime in with my $0.02:

    Add-LocalGroupMember -Group "Administrators" -Member "Some User"

    This is a built-in command, and, it just works. :)



    Sorry to deflate your obviously large cranium, but that was literally mentioned in the comments previous to yours. That command was only introduced in PS 5.1 (August 2016), so many people on this thread may still not be at that level.
    Friday, November 17, 2017 11:36 PM
  • Both of you geniuses should not that this topic is over 5 yers old.

    Stop being necrophiles.  Join the modern era.

    ;)


    \_(ツ)_/

    Friday, November 17, 2017 11:45 PM
  • Both of you geniuses should not that this topic is over 5 yers old.

    Stop being necrophiles.  Join the modern era.

    ;)


    \_(ツ)_/

    +1

    NecroPOSTphiles is a incurable disease 



    Gastone Canali >http://www.armadillo.it


    Se alcuni post rispondono al tuo quesito(non necessariamente i miei), ricorda di contrassegnarli come risposta e non dimenticare di contrassegnare anche i post utili. GRAZIE! Ricorda di dare un occhio ai link Click Here andHere

    Saturday, November 18, 2017 12:28 AM