Enforcing Computername using Intune Powershell

When performing a ‘Fresh Start’ or ‘Factory Reset’ on an Intune managed device, the computername is reset to the default ‘DESKTOP-<random>’ name.

Our requirement however, was that every machine has a specific computername.

Since Intune offers the possibility of deploying Powershell scripts, I’ve written one that checks the device’s serial number and renames the computer if the serial is known.

This script should not be run under the current user’s credentials, as by default they don’t have the right to change the computername.

NB: The changed computername will only become effective after a reboot

# Enforce Computername
# When a AD Joined device is given a fresh start or reset, the computername is reset to the default
# randomised 'DESKTOP-<random>' name; we had a requirement to enforce specific computernames for
# our devices
# 20180216 - Initial version

$VerbosePreference = "Continue"
$ErrorActionPreference = "Stop"
$LogFile = Join-Path $LogPath "CheckComputername.log"

Function Write-Log {
$Level = "INFO",



$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$Line = "$Stamp $Level $Message"
If($LogFile) {
Add-Content $LogFile -Value $Line
Write-Output $Line
Else {
Write-Output $Line
Function Get-VComputerName {[system.environment]::MachineName}

#Check if logpath exists
If(!(Test-Path $LogPath)){
# if logpath does not exist, create it
New-Item -ItemType Directory -Path $LogPath
#For debug purposes, record a transcript of the execution
Start-Transcript -Append -Path "${LogPath}CheckComputername.transaction.log"

$DeviceSerial = $(Get-WmiObject win32_bios | select -expand serialnumber)
$CurrentComputerName = Get-VComputerName
$hasError = $False
Write-Log -LogFile $LogFile -Message "Initialising Device Serial to Computername mapping" -Level DEBUG
$SerialNameTable= @{}

Write-Log -LogFile $LogFile -Message "Device Serial to Computername mapping size $($SerialNameTable.count)" -Level DEBUG

Write-Log -LogFile $LogFile -Message "Device Serial in names list"
if($CurrentComputerName -ne $SerialNameTable.$DeviceSerial){
Write-Log -LogFile $LogFile -Message "Computername $CurrentComputerName does not match list $($SerialNameTable.Item($DeviceSerial))" -Level ERROR
Write-Log -LogFile $LogFile -Message "renaming computer"
Rename-Computer -NewName $SerialNameTable.Item($DeviceSerial) -Force -ErrorAction Stop
} catch {
Write-Log -LogFile $LogFile -Message "Renaming failed; exception caught" -Level FATAL
Write-Log -LogFile $LogFile -Message "$($_.Exception.Message)" -Level DEBUG
} else {
Write-Log -LogFile $LogFile -Message "Computername matches list"
} else {
Write-Log -LogFile $LogFile -Message "Device Serial $DeviceSerial NOT in names list" -Level FATAL

exit 1
} else {
exit 0

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.