When re imaging devices, there is a need to automate as much as possible before the device gets shipped off to the user. One of the most important feature of the OSD process is domain joining the device. The post below reveals the source code needed to domain join a device based on the first block of string for device name.
Overview:
1. Create log files for the process
2. Grab the variables from the Task Sequence in order to use it in the script and converts it to PS variables. It essentially stores the credential during the admin sign in step then pass it off.
3. Detects your domain and place the computer in an OU based on the first block of string of the device name.
4. Post OU move- it injects a registry key value. This key is used for conditional evaluation of application deployment for task sequence. (If device belongs to Legal - deploy only legal apps to it) (Optional- can be removed)
Source code:
####################################################
# Create log folder
Write-Output "##### Creating Log folder #####"
$LogPath = "C:\Temp\MDT"
$TestPath = Test-Path -Path $LogPath
if($TestPath -eq $false ){
New-Item -Path $LogPath -ItemType "Directory"
}
# start logging
$LogFile = "$LogPath\MDT-DomainJoin_OU-$(Get-Date -Format 'MMddyyyy-HHmmss').log"
Start-Transcript -Path $LogFile -Force
#######################################################
# The function "ConvertFrom-Base64" converts the Base64 to UTF8 format
function ConvertFrom-Base64($stringfrom) {
$bytesfrom = [System.Convert]::FromBase64String($stringfrom);
$decodedfrom = [System.Text.Encoding]::UTF8.GetString($bytesfrom);
return $decodedfrom
}
####################################################
# Powershell must grab the variables from the Task Sequence in order to use it in the script
# This converts the TS variable to PS variables
$tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment
$tsenv.GetVariables() | % { Set-Variable -Name "$_" -Value "$($tsenv.Value($_))" }
####################################################
# Convert TS variables and declare them as varibles.
$ClearID = ConvertFrom-Base64 -stringfrom "$UserID"
$ClearDomain = ConvertFrom-Base64 -stringfrom "$UserDomain"
$ClearPW = ConvertFrom-Base64 -stringfrom "$UserPassword"
$User = "$ClearDomain\$ClearID"
$Password = ConvertTo-SecureString -String "$ClearPW" -AsPlainText -Force
# The "Credential" variable is the most critical part and will be required for interaction with AD and server
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User,$Password
####################################################
# Check what domain the device is part of:
$DeviceName = $env:COMPUTERNAME
$CompanyDomain = (Get-WmiObject Win32_ComputerSystem).Domain
# Split device name and grab only the first string/index[0] to be evaulated to determine its department.
$DeviceNameDept = $devicename.Split("-")[0]
# Invoke DC to move the comptuer object to the appropriate OU
$DCServer = "DC.red929.com"
####################################################
# Check if device is part of workgroup, if so, skip the entire script. Else, continue script.
if($CompanyDomain -eq "Workgroup"){
Write-Error "### Device is not part of domain ### `nSkipping OU move"
Exit
}# End if statment
####################################################
# If device is part of domain, move them to the following OU according to the first text before dash "-"
# Call DC to make the changes
$OU = Invoke-Command -ComputerName $DCServer -Credential $Credential -ThrottleLimit 100 -ScriptBlock {
# When using regex with -match in PowerShell, you can match against multiple possible patterns by separating them with the “OR” regex operator "|"
# Check if device name starts with Legal OR law by using regex operator "|"
if ($using:DeviceNameDept -match "Legal|Law") {
Write-Output "`n##### The device [$using:DeviceName] belongs to Legal department #####`n"
# Move Device to Legal OU
Write-Output "`nMoving Device to Legal OU.....`n"
Get-adcomputer $using:DeviceName | Move-ADObject -TargetPath "OU=Computers,OU=Legal,OU=New York,OU=Users and Computers,DC=Red929,DC=com" -Verbose -Confirm:$false
Start-sleep -Seconds 5
Write-Output "`n##### Organizational Unit (OU) move complete #####`n"
$DeviceDetails = Get-adcomputer $using:DeviceName | Select-Object name, DistinguishedName, ObjectGUID, ObjectClass
Write-Output "`nDevice Name: $($DeviceDetails.Name)`nOrganizational Unit: $($DeviceDetails.DistinguishedName)`nDevice GUID: $($DeviceDetails.ObjectGUID)`nObject: $($DeviceDetails.ObjectClass)"
"ID:Legal001"
}
}
#Output results
$OU
####################################################
#### Post OU Move ###
# Post OU move, a registry key will get created on the computer. The registry key is then evaulated by TS to determine which departmental application will be installed for the device.
# Each IF statement above will have specific ID string on it. Different registry key will be created depending on the ID string for $OU.
$RegKey = "HKLM:\Software\MDT"
if($OU -match "ID:Legal001"){
Write-Output "`n##### Creating new reg key for device under Legal (ID:Legal001)#####`n"
# Create Key
New-item -Path $RegKey -Verbose
# Create string value under key
New-ItemProperty -Path "$RegKey" -Name "ComputerOU" -Value "Legal" -PropertyType String -Force -Verbose
}
####################################################
#end logging
Stop-Transcript
Transcript log:
The following logs show the details generated after the domain join process completes. A warning appears indicating that the registry key already exists ($RegKey = "HKLM:\Software\MDT"). This warning can be safely ignored.
To prevent the warning message, you may consider adding a conditional check using Test-Path before creating the registry key, or use the -Force parameter to overwrite the existing key and suppress the error.
Transcript started, output file is C:\Temp\MDT\MDT-DomainJoin_OU-01302026-102549.log##### The device [IT-TEST-X09] belongs to Information Technology department #####Moving Device to Information Technology OU.....##### Organizational Unit (OU) move complete #####Device Name: IT-TEST-X09Organizational Unit: CN=IT-TEST-X09,OU=Computers,OU=Information Technology,OU=New York,OU=Users and Computers,DC=Red929,DC=comDevice GUID: 7ad287c4-afed-4d71-86ee-1277cd9b863aObject: computerID:IT002##### Creating new reg key for device under Information technology (ID:IT002) #####VERBOSE: Performing the operation "New Item" on target "Item: HKEY_LOCAL_MACHINE\Software\MDT".New-item : A key in this path already exists.At \\MDT\DeploymentShare$\Scripts\Powershell_Script\DomainJoin_OU.ps1:202 char:1+ New-item -Path $RegKey -Verbose+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (Microsoft.Power...RegistryWrapper:RegistryWrapper) [New-Item], IOException + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.NewItemCommandNew-item : A key in this path already exists.At \\MDT\DeploymentShare$\Scripts\Powershell_Script\DomainJoin_OU.ps1:202 char:1+ New-item -Path $RegKey -Verbose+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (Microsoft.Power...RegistryWrapper:RegistryWrapper) [New-Item] , IOException + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.NewItemCommandVERBOSE: Performing the operation "New Property" on target "Item: HKEY_LOCAL_MACHINE\Software\MDT Property: ComputerOU".ComputerOU : Information TechnologyPSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\MDTPSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SoftwarePSChildName : MDTPSDrive : HKLMPSProvider : Microsoft.PowerShell.Core\Registry**********************Windows PowerShell transcript endEnd time: 20260130102604**********************
