This PowerShell script automatically renames computers based on company standards and user information. This script is ideal for Entra-joined devices, as the UPN is used as a variable.
Format: ABC-JDOE-L##
# Configuration Variables
$CompanyPrefix = "ABC" # Abbreviation for the company name
$LogFilePath = "C:\\ComputerRenameLog.txt"
# Function to append log to the log file
function Write-Log {
Param ([string]$message)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $LogFilePath -Value "$timestamp - $message"
}
# Check if running on Server OS
$os = Get-WmiObject -Class Win32_OperatingSystem
if ($os.ProductType -ne 1) {
$logMessage = "This script is not designed to run on Server OS. Aborting."
Write-Log -message $logMessage
Write-Output $logMessage
exit
}
# Automatic Device Type Detection for Laptop or Desktop
if (Get-WmiObject -Class Win32_Battery) {
$deviceType = "L" # Assuming devices with a battery are laptops
} else {
$deviceType = "D" # Everything else will be considered a desktop
}
# Main Script
$upn = whoami.exe /upn
$userNamePrefix = $upn.Split('@')[0].ToUpper()
$userNamePrefix = $userNamePrefix.Substring(0, [Math]::Min(5, $userNamePrefix.Length))
$randomNumber = Get-Random -Minimum 10 -Maximum 99
$newName = "$CompanyPrefix-$userNamePrefix-$deviceType$randomNumber"
$currentComputerName = $env:COMPUTERNAME
$pendingRenameKeyPath = "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\ComputerName"
$activeComputerName = (Get-ItemProperty -Path "$pendingRenameKeyPath\\ActiveComputerName").ComputerName
$pendingComputerName = (Get-ItemProperty -Path "$pendingRenameKeyPath\\ComputerName").ComputerName
if ($activeComputerName -ne $pendingComputerName) {
$logMessage = "A computer rename is pending. Exiting script."
Write-Log -message $logMessage
exit
}
Rename-Computer -NewName $newName -Force
$logMessage = "The device has been renamed to $newName"
Write-Log -message $logMessage
Write-Output $logMessage