Add AD group to local administrators of the server

Today post will help you to understand how add AD group to local administrators.

Below script in first way is searching Active Directory for servers with Windows Server OS (this can be filtered deeper with LDAP filter adjustment).
Once all computers objects are gathered script create AD group. Name of the AD group uses pattern ADMComputerName.
When AD group is created it’s added to local administrators group of the server.
Simple script which can be used for most of the Active Directory environments 🙂

I almost forgot, at the begginning I’ve added Log function, which allows to see logs live in Powershell console or save them to file.

function Log{
        param(
	    [Parameter(Mandatory=$true, HelpMessage="Log line")][String] $Text
        )
       process{
	    $line = ($(Get-Date -Format "yyyy/MM/dd HH:mm:ss") + " - " + $Text)
	    if($Log -eq $true){
		    $stream = New-Object System.IO.StreamWriter($logpath, $true)
		    $stream.Write($line)
		    $stream.WriteLine()
		    $stream.Dispose()
	     }else{
    		Write-Host $line
	     }
       }
}
Write-Host "Script will find computers whith Windows Server operating system"
Write-Host "Script started..." 

$logPath = "C:\" + $(Get-Date -Format "yyyyMMdd_HHmmss") + '-LocalAdminGroupScript.log'
$Log=$true

Write-Host "Log file will be created under below path $logPath"

import-module ActiveDirectory


Try{
    $ADComputers = Get-ADComputer -LDAPFilter "(&(OperatingSystem=Windows Server*))" -Properties CanonicalName
}
Catch{
    $Exception = $_.Exception.Message
    Log ("Unexpected error occured: $Exception. Script will be stopped...")
}

$ComputersCounter = $ADComputers.Count
if($ComputersCounter -gt 0){
    Log("$ComputersCounter computers  found with Windows Server operating system")
    $ADComputers | %{
    
        $GroupName, $Exception, $ComputerName, $Domain, $TestGroup = $null
        $ComputerName = $_.Name
        $Domain = $_.CanonicalName.Split("/")[0]
        $GroupName = "ADM."+$ComputerName
        
        Try{
            $TestGroup = Get-ADGroup -Identity $GroupName -Server $Domain
        }
        Catch{
            $Exception = $_.Exception.Message
        }
        
        if($Exception -match "Cannot find an object with identity"){
            $Group = New-ADGroup -Name $GroupName -GroupScope DomainLocal -Server $Domain
            Log("AD group $Domain\$GroupName for computer $ComputerName has been created in default OU.")
        }
        elseif([string]::IsNullOrEmpty($Exception)){
            Log("AD group $Domain\$GroupName already exists for computer $ComputerName")
        }
        else{
            Log("Unexpected error occured during prerequisite check. $Exception")
        }

        $LocalAdminGroup = [ADSI]"WinNT://$ComputerName/Administrators"
        Try{
            $GroupObj.Add("WinNT://$Domain/$GroupName")
            Log("Group $Domain\$GroupName has been aded to local admin group on computer $ComputerName")
        }
        Catch{
            $Exception = ($_.Exception.Message).Split(":")[1].replace("account","group")
            Log("ADGroup: $Domain\$GroupName Computer: $ComputerName $Exception")
        }
            
        Try{
            $GroupObj.Remove("WinNT://$Domain/Domain Admins")
            Log("Domain admins group has been removed from local admin group on computer $ComputerName")
        }
        Catch{
            $Exception = ($_.Exception.Message).Split(":")[1].replace("account","group")
            Log("ADGroup: $Domain\Domain Admins Computer: $ComputerName $Exception")
        }
    }
}
else{
    Log("0 computers  found with Windows Server OS. Script will be stopped.")
}
Write-Host "Script finished, check log file."

Enjoy!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.