Using Intune Remediations to Rename Windows Devices

letterkenny-efficient

Like many of us, I’ve been using my good friend Michael Niehaus’ Rename Computer scripts via Intune Win32 Apps for quite awhile. The idea is simple, package these scripts as an app and deploy it down to a device. It will check if the naming convention is right and fix it!

So, what’s the problem? Well, it can be slow and may even take a few hours after that device comes out of the ESP. In addition, its another app that you have to wait for. Today, we’re going to cover my new solution leveraging Intune Remediations to streamline and make it a bit more efficient. Remember folks, if we can be one thing it should be efficient. We will cover:

Why are Naming Conventions an Issue?

We should start by covering the specific issue at hand.

When you build your Autopilot profile, you can setup a device naming template. If you’re a hybrid-joined device, you’re in bad shape because it only supports a prefix. So, you can say the prefix is “pizza” and devices will be like pizzaw3fjkf345 or something to that idea.

If you’re Entra-joined you have a few more options, e.g.: SYN-%SERIAL% (basically a prefix and a macro). They support macros for serial number or random number as part of your prefix. The gist is that it’s typically useless for any customer:

Screenshot of the Autopilot profile showing the device name template.

Ideally, more stuff would be supportable as it’s not what people are looking for overall. Enter the solution, I am here to discuss today.

Rename Computer Detection Script

We’re going to start with the script we use to detect the terrible name we have set to begin with. The code itself is hosted here. Let’s look at the code piece-by-piece to see what we’re working with.

First, we have code below to specify what computer prefix we want to check for. This is what checks to validate if the name it has currently is bad.

## Define the Computer Name Prefix to Check For ##
$Prefix = ""
Write-Host "Checking computer name prefix: $Prefix"
$details = Get-ComputerInfo

Next, we’re going to look at what join type the device is using and do a basic connectivity check if it’s an AD-joined device:


# See if we are AD or AAD joined
$isAD = $false
$isAAD = $false
$tenantID = $null
$goodToGo = $true

if ($details.CsPartOfDomain) {
    Write-Host "Device is joined to AD domain: $($details.CsDomain)"
    $isAD = $true
    $goodToGo = $false # Initialize as false; will validate connectivity below
} else {
    if (Test-Path "HKLM:/SYSTEM/CurrentControlSet/Control/CloudDomainJoin/JoinInfo") {
        $subKey = Get-Item "HKLM:/SYSTEM/CurrentControlSet/Control/CloudDomainJoin/JoinInfo"
        $guids = $subKey.GetSubKeyNames()
        foreach ($guid in $guids) {
            $guidSubKey = $subKey.OpenSubKey($guid)
            $tenantID = $guidSubKey.GetValue("TenantId")
        }
    }
    if ($null -ne $tenantID) {
        Write-Host "Device is joined to AAD tenant: $tenantID"
        $isAAD = $true
    } else {
        Write-Host "Not part of AAD or AD, in a workgroup."
    }
}

# AD connectivity check
if ($isAD) {
    $dcInfo = [ADSI]"LDAP://RootDSE"
    if ($null -eq $dcInfo.dnsHostName) {
        Write-Host "No connectivity to the domain, unable to rename at this point."
        $goodToGo = $false
    } else {
        Write-Host "Domain connectivity verified."
        $goodToGo = $true
    }
}

We will finish up by taking all of our discovery we did to determine if the name needs to be changed a.k.a, run the remediation!!

# Validate prefix and proceed only if conditions are met
if (($Prefix -ne "") -and (-not $details.CsName.StartsWith($Prefix)) -and $goodToGo) {
    Write-Host "Device name doesn't match specified prefix, time to update!"
    Exit 1
} else {
    Write-Output "$($details.CsName) is the current hostname."
}

If you’re a full cloud native environment, I got you fam! Check out my code below for Entra-joined detection:

##Define the Computer Name Prefix to Check For##
$Prefix = ""
Write-Host $Prefix
$details = Get-ComputerInfo
if (($Prefix -ne "") -and (-not $details.CsName.StartsWith($Prefix))) {
    Write-Host "Device name doesn't match specified prefix, time to update!"
    Exit 1
}
 else {
    Write-Output "$details.CsName is the current hostname."
}

Rename Computer Remediation Script

Once you have the detection script solid, you move onto your remediation. The full code for my rename computer script is here. Let’s slice this one up for fun because it’s neat how it works.

First, we will go and search for the Intune certificate in the local machine store and store the thumbprint into a variable:

# Define the target certificate store
$certStore = "Cert:\LocalMachine\My"

# Initialize $UPN variable
$UPN = $null

# Search for the Intune certificate based on the Issuer
$intuneCert = Get-ChildItem -Path $certStore | Where-Object {
    $_.Issuer -like "*CN=Microsoft Intune MDM Device CA*"
}
# Check if the certificate is found and capture the thumbprint
if ($intuneCert) { 
    $certThumbprint = $intuneCert.Thumbprint

With the thumbprint, we continue our investigation. We take that thumbprint to find the correct enrollment entry in the registry and capture the user’s UPN. Once we grab the UPN, we look for numbers in the name and grab them and store them in the $numbers variable:


    # Path to the enrollments registry key
    $enrollmentsPath = "HKLM:\SOFTWARE\Microsoft\Enrollments"

    # Loop through each subkey to match the DMPCertThumbPrint
    Get-ChildItem -Path $enrollmentsPath | ForEach-Object {
        $enrollment = Get-ItemProperty -Path $_.PSPath
        if ($enrollment.DMPCertThumbPrint -eq $certThumbprint) {
            # Store the UPN in the $UPN variable
            $UPN = $enrollment.UPN
        }
    }
}

# Proceed if $UPN is found
if ($UPN) {
    # Extract the numeric part (XXXX) from the UPN
    if ($UPN -match "\d+") {
        $numbers = $matches[0]
    } else {
        Write-Host "No numeric part found in UPN. Exiting script."
        Exit 1 # Exit with an error code
    }

Now, we will construct the computer name where we incorporate the $numbers variable into a more robust computer name. Next, we rename the computer, make sure its not in ESP/OOBE, and initiate a restart with a 10-minute runway (technically MSFT says don’t put in reboot, but mine is working well):

 
    # Construct the updated computer name
      $updatedComputerName = "SYN-$numbers-Corp"

    # Set the computer name
    Write-Host "Renaming computer to $($updatedComputerName)"
    Rename-Computer -NewName $updatedComputerName -Force

    # Make sure we reboot if still in ESP/OOBE by reporting a 1641 return code (hard reboot)
    if ($details.CsUserName -match "defaultUser") {
        Write-Host "Exiting during ESP/OOBE with return code 1641"
        Exit 1641
    } else {
        Write-Host "Initiating a restart in 10 minutes"
        & shutdown.exe /g /t 600 /f /c "Restarting the computer due to a computer name change. Save your work."
        Exit 0
    }
} else {
    Write-Host "No UPN found. Exiting script."
    Exit 1 # Exit with an error code
}

Deploying Remediation for Rename Computer in Intune

Deploying the remediation in Intune is pretty easy once you have written the scripts for it. Navigate directly to the script section. Once you’re there, you can upload the two scripts, and setup your assignments. For this specific remediation, I recommend setting it up as a run once, but you could have it run every day to ensure things stay compliant. That is based on your needs overall.

Check out the video below:

Facebook
Twitter
LinkedIn
The article discusses enhancing the efficiency of computer renaming within Intune through new scripts, as existing methods are slow and cumbersome. It details challenges with naming conventions, particularly for hybrid-joined devices, and presents detection and remediation scripts for improving the renaming process and ensuring compliance.

4 thoughts on “Using Intune Remediations to Rename Windows Devices”

  1. I think there will be some permissions issue for domain-joined computer. System account can’t rename DC records no?

    1. Basically you delegate permissions on the computer object folder to self which lets the computer rename itself.

      I’ll double check the article and see if I covered that. I don’t remember if I did

Leave a Reply to MobileJonCancel reply

Scroll to Top

Discover more from Mobile Jon's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading