Apologies for the delayed response. You can use Get-WinEvent
cmdlet to retrieve the last logged in user from Security event log. For example,
# Connect to Azure AD
Connect-AzureAD
# Get all devices in Azure AD
$devices = Get-AzureADDevice
# Loop through each device
foreach ($device in $devices) {
# Get the last logged-on user from the Security event log
$lastUser = Get-WinEvent -FilterHashtable @{LogName='Security';ID=4624;Data=$device.DeviceID} -MaxEvents 1 | Select-Object -ExpandProperty Properties | Where-Object {$_.ValueName -eq 'TargetUserName'} | Select-Object -ExpandProperty Value
# Update the primary user field in Azure AD
Set-AzureADDevice -ObjectId $device.ObjectId -DeviceTrustType Workplace -DevicePhysicalIds $device.DevicePhysicalIds -AccountEnabled $true -AlternativeSecurityIds $device.AlternativeSecurityIds -DisplayName $device.DisplayName -DeviceObjectVersion $device.DeviceObjectVersion -DeviceOSType $device.DeviceOSType -DeviceOSVersion $device.DeviceOSVersion -DeviceId $device.DeviceId -DeviceMetadata $device.DeviceMetadata -DeviceCategoryDisplayName $device.DeviceCategoryDisplayName -IsManaged $device.IsManaged -IsCompliant $device.IsCompliant -ApproximateLastLogonTimeStamp $device.ApproximateLastLogonTimeStamp -DeviceTrustLevel 0 -RegisteredOwners @($user.ObjectId)
}
You may need to make adjustments for your specific use case but hopefully this points you in right direction. Make sure to test in a test environment before running in production. You can use Test-AzureRmAutomationScript
cmdlet in Azure Automation.