Guest User

Untitled

a guest
Jul 3rd, 2025
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## Write the new name to registry key to use as detection
  2. function Detection {
  3.   # Write registry key to indicate success for detection
  4.   $path = 'HKLM:\SOFTWARE\COMPANYNAMEHERE\RenameToSerialNum'
  5.   if (!(Test-Path -LiteralPath $path)) { [void] (New-Item -Path $path -Force) }
  6.   Set-ItemProperty -Path $path -Name ConfigRev -Value 1 -Type DWord
  7. }
  8.  
  9. ## Function to search for computer name in AD without needing the AD powershell module
  10. function Get-ExistingComputer ($name) {
  11.   $Searcher = [ADSISearcher]"(&(objectClass=computer)(name=$($name)))"
  12.   $Searcher.SearchRoot = [ADSI]''
  13.   $Searcher.PropertiesToLoad.Add('Name')
  14.   $SearchResult = $Searcher.FindOne()    #note: exceptions can get thrown here
  15.   If ($SearchResult -And $SearchResult.Count -ne 0) {
  16.     $SearchResult.Properties
  17.   }
  18. }
  19.  
  20.  
  21. ## Check for connectivity to domain
  22. $dcInfo = [ADSI]"LDAP://your-domain-here.com"
  23. If ($null -eq $dcInfo.Path) {
  24.   Write-Error "No connectivity to AD"
  25.   Exit 1
  26. }
  27.  
  28. $oldName = $env:COMPUTERNAME
  29. ## Set new name to computer's serial number
  30. $newName = Get-WmiObject Win32_bios | Select-Object -ExpandProperty SerialNumber
  31.  
  32. ## Clean up serial, get rid of spaces, replace VMware- with VM, Max length 15
  33. $newName = $newName.Replace(' ', '')
  34. $newName = $newName.Replace('VMware-', 'VM')
  35. if ($newName.Length -ge 15) {
  36.   $newName = $newName.substring(0, 15)
  37. }
  38.  
  39. ## If the current hostname doesn't match the serial number, rename PC
  40. IF ($newName -ne $oldName) {
  41.   # See if the new name already exists in AD, if it does then exit 1. The old AD object needs to be removed.
  42.   IF (Get-ExistingComputer -name $newName) {
  43.     write-Output "Computer $newName already exists!! Need to delete in AD"
  44.     Exit 1
  45. }
  46.  
  47.   Try {
  48.     Rename-Computer -NewName $newName -erroraction stop
  49.   } Catch {
  50.     Write-Output "Error: $_"
  51.     Exit 1
  52.   }
  53.  
  54.  
  55.   Write-Output "Computer renamed from $oldName to $newName"
  56.  
  57.   # Write detection reg key
  58.   Detection
  59.   # Require hard restart
  60.   Exit 1641
  61. } ELSE {
  62.   ## The computer is already the correct name, exit 0 to indicate success
  63.   # Write detection reg key
  64.   Detection
  65.   Exit 0
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment