PowerShell: Create AD computer objects as per the given details in the list

Sometimes admin need to pre-create AD computer object in correct OU as per the user and update the user’s information it belongs to in the Managed By field.

Below script will receive input as list of computers and their corresponding users to whom the machine will be assigned.

Create two files in C:\Temp directory:

  1. ComputerList.txt – This file will contain list of machine names that need to be created in AD
  2. UserList – This file will contain users display name that already exists in AD

The script will check user object is created in which OU and will create the machine object in relevant machines OU.

You will have to update the script in case you want the machine object to be created in different OU.

# Script to create AD computer objects as per the given details in the list.
#
# Please create two normal text files with below information:
# 1. Computer Names
# 2. Users Display Name as found in Active Directory
# 3. Please update the file paths below in the variables defined to store the data in arrays.
#    $CompNameList
#    $UserList
#

Clear-Host

# Import Active Directory PS-Module to run the AD commandlets
Import-Module ActiveDirectory

# Defining variables and their types as ARRAY
$CompNameList = [System.Collections.ArrayList]@()
$UserList = [System.Collections.ArrayList]@()

# Importing values in variables
$CompNameList = @(Get-Content C:\Temp\ComputerList.txt)
$UserList = @(Get-Content C:\Temp\UserList.txt)

$n = -1

foreach ($CompName in $CompNameList)
{
    $n++

    $CompName = $CompNameList["$n"]
    $User = $UserList["$n"]

    $UserDept = (Get-ADUser -SearchBase "OU=INT,DC=lab,DC=com" -Server DC01.lab.com -Filter "DisplayName -like '$User'" -Properties * | Select-Object -ExpandProperty Department)

    $UserSAMAccountName = (Get-ADUser -SearchBase "OU=INT,DC=lab,DC=com" -Server DC01.lab.com -Filter "DisplayName -like '$User'" -Properties * | Select-Object -ExpandProperty SAMAccountName)

    Write-Output "Computer: $CompName --- DisplayName: $User --- UserSAMAccount: $UserSAMAccountName --- Dept: $UserDept"

    # Creating New AD Computer Object based on above variables
    New-ADComputer `
    -Name "$CompName" `
    -Path "OU=Machines,OU=$UserDept,OU=INT,DC=lab,DC=com" `
    -Enabled $True `
    -ManagedBy "$UserSAMAccountName" `
    -Server DC01.lab.com

    # Pause for 5 seconds for AD to update the new account values 
    Start-Sleep -Seconds 5

    # Adding Default AD Groups and DEPT-AD Groups
    Add-ADPrincipalGroupMembership -Server DC01.lab.com -Identity "$CompName$" -MemberOf "Lab - All Machines", "$UserDept - All Machines"
    
    # If device is Laptop then Add "Lab - All Laptops"
    if ($CompName -like "NB*")
    {
        Add-ADPrincipalGroupMembership -Server DC01.lab.com -Identity "$CompName$" -MemberOf "Lab - All Laptops"
    }
}