Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RunOnce to rename a Computername with a random name on reboot

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!

like image 475
Menkadelic Avatar asked Nov 22 '25 18:11

Menkadelic


1 Answers

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.

like image 58
KevinD Avatar answered Nov 24 '25 09:11

KevinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!