Automated script to update primary users

Callan Contrino 0 Reputation points
2023-08-16T11:20:47.15+00:00

Hi there,

Hope you are all well, I'm wondering if anyone can help in pointing me in the right direction.

Essentially, we have a lot of devices which have the incorrect primary user set, primarily from IT setup which we has since changed. The main goal for this is to update each device's primary user with the last logged on user, making it run on an Azure automation every couple of weeks. I would prefer to run a test version of the script first, though.

Does anyone know of an up to date script? I have tried a couple but can't seem to get them to work.

Many thanks

Azure Automation
Azure Automation
An Azure service that is used to automate, configure, and install updates across hybrid environments.
1,366 questions
Microsoft Security Microsoft Graph
{count} votes

1 answer

Sort by: Most helpful
  1. Ryan Hill 30,281 Reputation points Microsoft Employee Moderator
    2023-08-22T15:53:54.8133333+00:00

    Hi @Callan Contrino

    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.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.