I have written this short powershell script to rename a computer as part of an MDT task sequence:
Import-Module ActiveDirectory
$AdminUsername = 'domain.com\administrator'
$AdminPassword = 'password' | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $AdminUsername, $AdminPassword
$Domain = Get-ADDomainController –DomainName domain.com -Discover -NextClosestSite
$Site = $Domain.Site
$DomainComputer = Get-WmiObject Win32_BIOS
$Serial = $DomainComputer.SerialNumber
$Computername = $Site + "-" + $Serial
Rename-Computer -NewName $Computername -DomainCredential $cred
When MDT runs this task, it runs it as the local administrator. I get the following error when it attempts to load the AD Module.
Warning: Error initializing default drive: 'The server has rejected the client credentials.'.
I can import the module just fine after the task sequence is over from the machine when logged in as a domain admin, but not as the local administrator of the machine. Is there any way to run the MDT task sequence as a domain administrator or elevate the privileges of the local administrator during the task sequence?
Thanks in advance for any help you can provide,
Mx
UPDATE: 10/13/2015
I decided to move away from using the AD module within my MDT script and shortly after posting this devised another way of getting this done. My results with the AD module were unpredictable at best. I wanted to post it here for posterity. I add this to the State Restore > Custom Tasks folder as a "Run Powershell Script" in my MDT task sequence and then add a Restart Computer task directly underneath it. It's been working like a charm on a 1600+ client deployment this past year.
$type = [System.DirectoryServices.ActiveDirectory.DirectoryContextType]"Domain"
$context = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext($type, "yourdomain.edu", "domainadmin", "yourpasswordhere")
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($context)
$DC = $domain.FindDomainController().Name
$Prefix = $DC.Substring(0,5)
$DomainComputer = Get-WmiObject Win32_BIOS
$Serial = $DomainComputer.SerialNumber
$Computername = $Prefix + "-" + $Serial
$Password = "yourpasswordhere"
$Username = "yourdomain.edu\domainadmin"
$Computer = Get-WmiObject Win32_ComputerSystem
$Computer.Rename($Computername,$Password,$Username)