RunOnce to rename a Computername with a random name on reboot

Menkadelic picture Menkadelic · Feb 10, 2014 · Viewed 8k times · Source

We are a learning center and sometimes we are not able to sysprep the machines for different reasons. When I do not sysprep the machines, I end up cloning a machine 25 times with the same computername.

I then have to go manually on each station and change the computername and restart them after.

I was wondering if I could use a batch file or powershell script that I would do before shutting down my machine (pre-cloning). Then, on next reboot (only once) the computer would randomly change the Computername and therefore save me alot of time.

I am doing this under Windows XP to Windows Server 2012R2. A unique solution working under all those OSes would be magic but I mostly do this on Server 2008+. I dont mind using a batch file for WinXP-Win7 and powershell for Windows 2008 to 2012 for example!

Thank you everyone!

Answer

KevinD picture KevinD · Feb 10, 2014

You can generate a random name using the Get-Random cmdlet.

# Set allowed ASCII character codes to Uppercase letters (65..90), 
$charcodes = 65..90

# Convert allowed character codes to characters
$allowedChars = $charcodes | ForEach-Object { [char][byte]$_ }

$LengthOfName = 10
# Generate computer name
$pw = ($allowedChars | Get-Random -Count $LengthOfName) -join ""

You can change a computer name with the cmdlet Rename-Computer. And to set it to run once, the easiest way would be to add an entry to the registry key

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce   

that will invoke PowerShell with your script.