PowerShell: Add Domain User to Local Administrators Group on All Servers In An OU

A co-worker needed to add a specified user to the local administrators group to all the servers in a specific Organizational Unit (OU), across 3 different sub-domains. Because of the different domains and service account names the script required that I prompt the user for input. After several hours (I am still very much learning PowerShell), this is what I came up with, and it worked like a charm.  Any suggestions/recommendations are greatly appreciated.

This blog was extremely helpful in piecing together the last parts that I needed.

$Domain = Read-Host 'What is the domain? Ex: DOMAIN'
$ServiceAcct = Read-Host 'What is the service account? EX: TEST'
$FullDomain = "$Domain.COM"
$ComputerList = Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=$Domain,DC=COM" -Server "$Domain.COM" | 
ForEach-Object {
    $Server=$_.Name

    $objUser = [ADSI]("WinNT://$Domain/$ServiceAcct")
    $objGroup = [ADSI]("WinNT://$Server/Administrators")
    $objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)
}

PowerShell: Make Changes to CSV for Import Into ADLS Instance

We have an Active Directory Lightweight Directory Services (ADLS) instance that houses users for a custom application.  When new users need to be added to the instance we get a spreadsheet with the user’s names and their usernames.  I needed to figure out a way to import this .CSV, add columns with the appropriate information for import into the ADLS instance.

This is what I came up with.  If there is a “better” or more compact way to do this please feel free to let me know how to do so in the comments.  This is one of the first PowerShell scripts I have ever written and I have a lot to learn.

 

# Import the CSV
$userobjects = Import-CSV C:usersimport.csv
# Run through each user in the CSV
& { ForEach ($userObject in $userObjects){
# Assign variables I need to be able to import into the ADLS instance
     $Name = $user.username
     $CN = $user.username
     $OU = $user.vendorcode
     $DisplayName = $user.Username
     $userPrincipalName = $user.username
     $UID = $user.username

# Create the objects for output
     New-Object -TypeName PSObject -Property @{
        DN = "CN=$Name,CN=PRD-VENDORS,DC=DOMAIN,DC=local"
        objectClass = "user"
        distinguishedName = "CN=$Name,CN=PRD-VENDORS,DC=DOMAIN,dc=local"
        name = $Name
        objectCategory = "CN=Person,CN=Schema,CN=Configuration,CN={03D4235C-46B8-4668-B88D-566EDD61100D}"
        cn = $CN
        ou = $OU
        displayName = $DisplayName
        userPrincipalName = $userPrincipalName
        uid = $UID

# Pipe the the objects in the order I need them to display in the CSV

        } | Select-Object DN,objectClass,distinguishedName,name,objectCategory,cn,ou,displayName,userPrincipalName,uid | 
            Export-CSV C:Users.csv -NoTypeInformation

     }