Forum Discussion
Device Rename in HAADJ environment
Tony,
If you have SCCM at your site you can create a task sequence to run on the computer that will run a PowerShell script. The collection looks for computers with the pre-fix as part of the computer name (like AUTOPILOTPCXXXX) The script will query the BIOS to see if an asset tag is programed into it and then rename the computer to me new prefix+Asset tag. Now the computer does have to be on the network, VPN or in the office as the script is updating the AD record which will then get updated on the Azure/Intune side. The script will search AD to see if a computer object with the same name exists remove it if found, you can also have it search for the computer in SCCM and remove it
Its not perfect but its been working for me.
Set-ExecutionPolicy Bypass -Scope Process -Force
$oldCompName = $env:COMPUTERNAME
$AssetTag = (Get-WmiObject Win32_SystemEnclosure).SMBiosAssetTag
$serial = Get-WmiObject win32_bios | select -expand serialnumber
$sccmServer='SCCMSERVERNAME'
$sccmSite='SITECODE'
Reset-ComputerMachinePassword
Start-Transcript "C:\Windows\PKGCache\LOG\RenameComputer.log" -Append
If (($AssetTag) -and ($AssetTag -ne "No Asset Information"))
{
$newname = "PREFIX" + $AssetTag -replace '[^a-zA-Z0-9]', ''
#Rename-Computer -NewName $newname -Force
}
Elseif ((!$AssetTag) -or ($AssetTag -eq "No Asset Information"))
{
$newname = "PREFIX" + $serial -replace '[^a-zA-Z0-9]', ''
#Rename-Computer -NewName $newname -Force
}
$validname = $newname.substring(0, [System.Math]::Min(14, $newname.Length))
Write-host "Old Computer name $oldcompname"
Write-host "New computer name $validname"
if ($validname -eq "PREFIX")
{$validname = "PREFIX" + (Get-random -Maximum 1000000)}
else
{Write-Host "Computer is named $validname, proceeding"}
# find and delete the computer from AD
If ($env:COMPUTERNAME -eq $Validname)
{Stop-Transcript
Exit}
ELSE
{$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $dom.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.filter = "(&(objectclass=computer)(name=$validname))"
$search.findall() | %{$_.GetDirectoryEntry() } | %{$_.DeleteObject(0)}}
Start-Sleep -seconds 60
# Rename computer to new name
If ($env:COMPUTERNAME -eq $validname)
{Stop-Transcript
Exit}
Else
{Rename-Computer -NewName $validname -Force}
Stop-Transcript