Add a Domain Group to Local Administrators Group

$checkGroup="Administrators"
$addMember="KIMCONNECT\Desktop Admins"

# Dynamic Credential
$who = whoami
	if ($who.substring($who.length-2, 2) -eq "-admin"){$username=$who;}
    else {$username=$who+"-admin";}
$password = Read-Host -Prompt "Input the password for account $username" -AsSecureString
#$password=convertto-securestring "PASSWORD" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password

$servers=Read-Host -Prompt 'Please copy/paste servers list'
$servers= $servers -split '\r\n'
#$servers="localhost"

$servers | foreach {
    Invoke-command -Credential $cred -ComputerName $_ -ScriptBlock {
        
        Import-Module ActiveDirectory
        
        $person=$Args[0]
        $add=$Args[1]
        $targetGroup=$Args[2]
        $computer=$Args[3]
        "Invoked from $person and Running as: "+ (whoami)+" on target: "+(hostname)+"`n"
        
        $members=Get-LocalGroupMember -Name $targetGroup
        #$members = Get-ADGroupMember -Identity $Args[2] -Recursive | Select -ExpandProperty Name
        #net localgroup [string]$tGroup | select -Skip 6 | select -SkipLast 2
        #$groupMembers=(net localgroup $Args[2] | select -Skip 6 | select -SkipLast 2)
     
        if ($members.Name -contains $add){"$computer`: $add already exists in group $targetGroup`n";}
        else{
            "$Args[1] is not a member of group $targetGroup. It is now being added...`n"
            NET USER $add /ADD /Y
            NET LOCALGROUP $targetGroup $add /ADD /Y
            $members=Get-LocalGroupMember -Name $targetGroup
            }
        "$computer`: Group $targetGroup now has these members..."
        $members.Name

        # These lines only work in PowerShell 5.1
        #New-LocalUser $Args[1] -Password $Args[2] -FullName $Args[3] -Description $Args[4]
        #Add-LocalGroupMember -Group $Args[5] -Member $Args[1]
        
    } -Args $who,$addMember,$checkGroup,$_
}

Leave a Reply

Your email address will not be published. Required fields are marked *