// script
Computer Rename Script (Based on UPN)
PowerShell script that renames Entra-joined Windows devices using the signed-in user's UPN.
Apr 4, 2025
Windows Intune Entra
PS> iwr https://www.cloudytechbrain.com/scripts/computer-rename-upn/raw.ps1 | iex
Script Overview
This PowerShell script automatically renames computers based on company standards and user information. Ideal for Entra-joined devices, as the UPN is used as a variable.
Key Components
- Configuration: sets company prefix and log file location.
- Logging: timestamp-based logging.
- OS validation: checks that this is not a server OS.
- Device type: automatically determines laptop vs desktop (battery presence).
- Naming logic:
ABC-JDOE-L## - company prefix, up to 5 UPN chars, device type (L/D), random 10–99. - Safety checks: verifies no pending rename operations.
Format
ABC-JDOE-L##
ABC - company prefixJDOE - first 5 characters of the usernameL or D - laptop or desktop## - random number 10–99
# 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
← Back