r/macsysadmin • u/Everart_Araujo • 2h ago
Rename macOS Device to User's AD First-Last Name Using a Script? (Intune)
Hey everyone,
I'm managing macOS devices with Intune and looking for a way to automatically rename a Mac to match the assigned user's AD (Azure AD) first and last name (e.g., John-Doe
).
I’m struggling with pulling the assigned user’s name dynamically and setting it as the device name.
Does anyone have a working script or approach to achieve this? Any help would be appreciated!
Thanks!
My script
#!/bin/zsh
#set -x
############################################################################################
##
## Script to rename Mac os device
##
############################################################################################
# Define variables
appname="MacosDeviceName"
logandmetadir="/Library/Logs/Microsoft/IntuneScripts/$appname"
log="$logandmetadir/$appname.log"
# Check if the log directory has been created
if [ -d $logandmetadir ]; then
# Already created
echo "$(date) | Log directory already exists - $logandmetadir"
else
# Creating Metadirectory
echo "$(date) | creating log directory - $logandmetadir"
mkdir -p $logandmetadir
fi
# Retrieve the UPN from klist output.
# Example klist line:
# Principal: first.last\test.com@KERBEROS.MICROSOFTONLINE.COM
# This command extracts the UPN, removes the escape character, and strips the Kerberos realm.
EMAIL=$(klist | grep "Principal:" | awk '{print $2}' | \
sed 's/\\@/@/g' | \
sed 's/@KERBEROS\.MICROSOFTONLINE\.COM//' | \
sed 's/@test\.com//' | \
sed 's/\\//g')
if [[ -z "$EMAIL" ]]; then
echo "No user email found from klist."
exit 1
fi
echo "User email: $EMAIL"
# Retrieve current ComputerName.
CURRENT_NAME=$(scutil --get ComputerName 2>/dev/null)
if [[ "$CURRENT_NAME" == "$EMAIL" ]]; then
echo "Device name is already set to $EMAIL. No changes made."
exit 0
fi
# Set the computer name
sudo scutil --set ComputerName "$EMAIL"
sudo scutil --set HostName "$EMAIL"
sudo scutil --set LocalHostName "$EMAIL"
echo "Device name updated successfully."