├── README.md ├── DirectPrint └── DirectPrint.ps1 └── PrimaryUser ├── Set-PrimaryUserUnattended.ps1 └── Set-PrimaryUserfromLastLogIn.ps1 /README.md: -------------------------------------------------------------------------------- 1 | # IntuneScripts 2 | -------------------------------------------------------------------------------- /DirectPrint/DirectPrint.ps1: -------------------------------------------------------------------------------- 1 | #-----------Set Printer Variables-----------# 2 | $PrinterName = "Resource Copier" 3 | $PrinterIP = "192.168.2.23" 4 | $DriverName = "PCL6 Driver for Universal Print" 5 | $LogFile = "C:\Temp\Logs\AddPrinter.log" 6 | 7 | 8 | #-----------Start Script-----------# 9 | $Date = Get-Date 10 | 11 | #Install drivers delivered with the Intune Package. 12 | start-process .\dpinst64.exe -ArgumentList "/S /SE /SW" 13 | Sleep 10 14 | 15 | #Check if the printer driver exists, if not, create it. 16 | If (Get-PrinterDriver $DriverName){ 17 | Write-Output "$Date - Printer Driver $DriverName - Already Exists" | Out-File -Append $LogFile 18 | } 19 | Else{ 20 | Try{ 21 | Add-PrinterDriver -Name $DriverName 22 | } 23 | Catch{ 24 | $ErrorMessage = $_.Exception.Message 25 | $ErrorMessage | Out-File -Append $LogFile 26 | } 27 | } 28 | 29 | #Check if the local printer port exists, if not, create it. 30 | If (Get-PrinterPort "TCP:$($PrinterName)"){ 31 | Write-Output "$Date - Printer Port TCP:$($PrinterName) - Already Exists" | Out-File -Append $LogFile 32 | } 33 | Else { 34 | Try{ 35 | Add-PrinterPort -Name "TCP:$($PrinterName)" -PrinterHostAddress $PrinterIP 36 | } 37 | Catch{ 38 | $ErrorMessage = $_.Exception.Message 39 | $ErrorMessage | Out-File -Append $LogFile 40 | } 41 | } 42 | 43 | #Check if the printer exists, if no, add it and set the configuration. 44 | If (Get-Printer $($PrinterName)){ 45 | Write-Output "$Date - Printer $PrinterName - Already Exists" | Out-File -Append $LogFile 46 | } 47 | Else { 48 | Try{ 49 | Add-Printer -Name "$($PrinterName)" -PortName "TCP:$($PrinterName)" -DriverName $DriverName -Shared:$false 50 | Get-Printer $($PrinterName) | Set-PrintConfiguration -DuplexingMode OneSided -Color $false 51 | } 52 | Catch{ 53 | $ErrorMessage = $_.Exception.Message 54 | $ErrorMessage | Out-File -Append $LogFile 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /PrimaryUser/Set-PrimaryUserUnattended.ps1: -------------------------------------------------------------------------------- 1 | # Application (client) ID, tenant ID and secret 2 | $clientId = "YOUR CLIENT ID HERE" 3 | $clientSecret = "YOUR CLIENT SECRET" 4 | $tenantid = "YOUR TENANT ID" 5 | 6 | #################################################### 7 | 8 | function Get-AuthToken { 9 | $script:graphBaseURI = "https://graph.microsoft.com/beta" 10 | 11 | # Construct URI 12 | $uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" 13 | 14 | # Construct Body 15 | $body = @{ 16 | client_id = $clientId 17 | scope = "https://graph.microsoft.com/.default" 18 | client_secret = $clientSecret 19 | grant_type = "client_credentials" 20 | } 21 | 22 | # Get OAuth 2.0 Token 23 | $tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing 24 | 25 | # Access Token 26 | $script:token = ($tokenRequest.Content | ConvertFrom-Json).access_token 27 | 28 | $ExpiresOn = [DateTimeOffset](get-date).AddMinutes(3599) 29 | 30 | $authHeader = @{ 31 | 'Content-Type'='application/json' 32 | 'Authorization'="Bearer " + $token 33 | 'ExpiresOn'= $ExpiresOn 34 | } 35 | 36 | return $authHeader 37 | } 38 | 39 | 40 | #################################################### 41 | 42 | function Get-Win10IntuneManagedDevice { 43 | 44 | <# 45 | .SYNOPSIS 46 | This gets information on Intune managed devices 47 | .DESCRIPTION 48 | This gets information on Intune managed devices 49 | .EXAMPLE 50 | Get-Win10IntuneManagedDevice 51 | .NOTES 52 | NAME: Get-Win10IntuneManagedDevice 53 | #> 54 | 55 | [cmdletbinding()] 56 | 57 | param 58 | ( 59 | [parameter(Mandatory=$false)] 60 | [ValidateNotNullOrEmpty()] 61 | [string]$deviceName 62 | ) 63 | 64 | $graphApiVersion = "beta" 65 | 66 | try { 67 | 68 | if($deviceName){ 69 | 70 | $Resource = "deviceManagement/managedDevices?`$filter=deviceName eq '$deviceName'" 71 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)" 72 | 73 | (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).value 74 | 75 | } 76 | 77 | else { 78 | 79 | $Resource = "deviceManagement/managedDevices?`$filter=(((deviceType%20eq%20%27desktop%27)%20or%20(deviceType%20eq%20%27windowsRT%27)%20or%20(deviceType%20eq%20%27winEmbedded%27)%20or%20(deviceType%20eq%20%27surfaceHub%27)))" 80 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)" 81 | 82 | (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).value 83 | 84 | } 85 | 86 | } catch { 87 | $ex = $_.Exception 88 | $errorResponse = $ex.Response.GetResponseStream() 89 | $reader = New-Object System.IO.StreamReader($errorResponse) 90 | $reader.BaseStream.Position = 0 91 | $reader.DiscardBufferedData() 92 | $responseBody = $reader.ReadToEnd(); 93 | Write-Host "Response content:`n$responseBody" -f Red 94 | Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" 95 | throw "Get-IntuneManagedDevices error" 96 | } 97 | 98 | } 99 | 100 | #################################################### 101 | 102 | Function Get-AADUser(){ 103 | 104 | <# 105 | .SYNOPSIS 106 | This function is used to get AAD Users from the Graph API REST interface 107 | .DESCRIPTION 108 | The function connects to the Graph API Interface and gets any users registered with AAD 109 | .EXAMPLE 110 | Get-AADUser 111 | Returns all users registered with Azure AD 112 | .EXAMPLE 113 | Get-AADUser -userPrincipleName user@domain.com 114 | Returns specific user by UserPrincipalName registered with Azure AD 115 | .NOTES 116 | NAME: Get-AADUser 117 | #> 118 | 119 | [cmdletbinding()] 120 | 121 | param 122 | ( 123 | $userPrincipalName, 124 | $Property 125 | ) 126 | 127 | # Defining Variables 128 | $graphApiVersion = "v1.0" 129 | $User_resource = "users" 130 | 131 | try { 132 | 133 | if($userPrincipalName -eq "" -or $userPrincipalName -eq $null){ 134 | 135 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)" 136 | (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value 137 | 138 | } 139 | 140 | else { 141 | 142 | if($Property -eq "" -or $Property -eq $null){ 143 | 144 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)/$userPrincipalName" 145 | Write-Verbose $uri 146 | Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get 147 | 148 | } 149 | 150 | else { 151 | 152 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)/$userPrincipalName/$Property" 153 | Write-Verbose $uri 154 | (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value 155 | 156 | } 157 | 158 | } 159 | 160 | } 161 | 162 | catch { 163 | 164 | $ex = $_.Exception 165 | $errorResponse = $ex.Response.GetResponseStream() 166 | $reader = New-Object System.IO.StreamReader($errorResponse) 167 | $reader.BaseStream.Position = 0 168 | $reader.DiscardBufferedData() 169 | $responseBody = $reader.ReadToEnd(); 170 | Write-Host "Response content:`n$responseBody" -f Red 171 | Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" 172 | write-host 173 | break 174 | 175 | } 176 | 177 | } 178 | 179 | #################################################### 180 | 181 | function Get-IntuneDevicePrimaryUser { 182 | 183 | <# 184 | .SYNOPSIS 185 | This lists the Intune device primary user 186 | .DESCRIPTION 187 | This lists the Intune device primary user 188 | .EXAMPLE 189 | Get-IntuneDevicePrimaryUser 190 | .NOTES 191 | NAME: Get-IntuneDevicePrimaryUser 192 | #> 193 | 194 | [cmdletbinding()] 195 | 196 | param 197 | ( 198 | [Parameter(Mandatory=$true)] 199 | [string] $deviceId 200 | ) 201 | $graphApiVersion = "beta" 202 | $Resource = "deviceManagement/managedDevices" 203 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)" + "/" + $deviceId + "/users" 204 | 205 | try { 206 | 207 | $primaryUser = Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get 208 | 209 | return $primaryUser.value."id" 210 | 211 | } catch { 212 | $ex = $_.Exception 213 | $errorResponse = $ex.Response.GetResponseStream() 214 | $reader = New-Object System.IO.StreamReader($errorResponse) 215 | $reader.BaseStream.Position = 0 216 | $reader.DiscardBufferedData() 217 | $responseBody = $reader.ReadToEnd(); 218 | Write-Host "Response content:`n$responseBody" -f Red 219 | Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" 220 | throw "Get-IntuneDevicePrimaryUser error" 221 | } 222 | } 223 | 224 | #################################################### 225 | 226 | function Set-IntuneDevicePrimaryUser { 227 | 228 | <# 229 | .SYNOPSIS 230 | This updates the Intune device primary user 231 | .DESCRIPTION 232 | This updates the Intune device primary user 233 | .EXAMPLE 234 | Set-IntuneDevicePrimaryUser 235 | .NOTES 236 | NAME: Set-IntuneDevicePrimaryUser 237 | #> 238 | 239 | [cmdletbinding()] 240 | 241 | param 242 | ( 243 | [parameter(Mandatory=$true)] 244 | [ValidateNotNullOrEmpty()] 245 | $IntuneDeviceId, 246 | [parameter(Mandatory=$true)] 247 | [ValidateNotNullOrEmpty()] 248 | $userId 249 | ) 250 | $graphApiVersion = "beta" 251 | $Resource = "deviceManagement/managedDevices('$IntuneDeviceId')/users/`$ref" 252 | 253 | try { 254 | 255 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)" 256 | 257 | $userUri = "https://graph.microsoft.com/$graphApiVersion/users/" + $userId 258 | 259 | $id = "@odata.id" 260 | $JSON = @{ $id="$userUri" } | ConvertTo-Json -Compress 261 | 262 | Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON -ContentType "application/json" 263 | 264 | } catch { 265 | $ex = $_.Exception 266 | $errorResponse = $ex.Response.GetResponseStream() 267 | $reader = New-Object System.IO.StreamReader($errorResponse) 268 | $reader.BaseStream.Position = 0 269 | $reader.DiscardBufferedData() 270 | $responseBody = $reader.ReadToEnd(); 271 | Write-Host "Response content:`n$responseBody" -f Red 272 | Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" 273 | throw "Set-IntuneDevicePrimaryUser error" 274 | } 275 | 276 | } 277 | 278 | #################################################### 279 | 280 | #region Authentication 281 | 282 | write-host 283 | 284 | # Checking if authToken exists before running authentication 285 | if($global:authToken){ 286 | 287 | # Setting DateTime to Universal time to work in all timezones 288 | $DateTime = (Get-Date).ToUniversalTime() 289 | 290 | # If the authToken exists checking when it expires 291 | $TokenExpires = ($authToken.ExpiresOn.datetime - $DateTime).Minutes 292 | 293 | if($TokenExpires -le 0){ 294 | 295 | write-host "Authentication Token expired" $TokenExpires "minutes ago" -ForegroundColor Yellow 296 | write-host 297 | 298 | # Defining User Principal Name if not present 299 | 300 | #if($User -eq $null -or $User -eq ""){ 301 | # $User = Read-Host -Prompt "Please specify your user principal name for Azure Authentication" 302 | # Write-Host 303 | #} 304 | 305 | $global:authToken = Get-AuthToken # -User $User 306 | } 307 | } 308 | 309 | # Authentication doesn't exist, calling Get-AuthToken function 310 | 311 | else { 312 | 313 | #if($User -eq $null -or $User -eq "") { 314 | # $User = Read-Host -Prompt "Please specify your user principal name for Azure Authentication" 315 | # Write-Host 316 | #} 317 | 318 | # Getting the authorization token 319 | $global:authToken = Get-AuthToken # -User $User 320 | } 321 | 322 | #endregion 323 | 324 | #################################################### 325 | 326 | #Get All Windows 10 Intune Managed Devices for the Tenant 327 | $Devices = Get-Win10IntuneManagedDevice 328 | 329 | $targetdevices = $devices | Where-Object {$_.deviceName -like "LAP*"} 330 | 331 | 332 | Foreach ($Device in $targetdevices){ 333 | 334 | Write-Host "Device name:" $device."deviceName" -ForegroundColor Cyan 335 | $IntuneDevicePrimaryUser = Get-IntuneDevicePrimaryUser -deviceId $Device.id 336 | 337 | #Check if there is a Primary user set on the device already 338 | if($IntuneDevicePrimaryUser -eq $null){ 339 | 340 | Write-Host "No Intune Primary User Id set for Intune Managed Device" $Device."deviceName" -f Red 341 | 342 | } 343 | 344 | else { 345 | $PrimaryAADUser = Get-AADUser -userPrincipalName $IntuneDevicePrimaryUser 346 | Write-Host "Intune Device Primary User:" $PrimaryAADUser.displayName 347 | 348 | } 349 | 350 | #Get the objectID of the last logged in user for the device, which is the last object in the list of usersLoggedOn 351 | $LastLoggedInUser = ($Device.usersLoggedOn[-1]).userId 352 | 353 | #Using the objectID, get the user from the Microsoft Graph for logging purposes 354 | $User = Get-AADUser -userPrincipalName $LastLoggedInUser 355 | 356 | #Check if the current primary user of the device is the same as the last logged in user 357 | if($IntuneDevicePrimaryUser -notmatch $User.id){ 358 | 359 | #If the user does not match, then set the last logged in user as the new Primary User 360 | $SetIntuneDevicePrimaryUser = Set-IntuneDevicePrimaryUser -IntuneDeviceId $Device.id -userId $User.id -ErrorAction SilentlyContinue 361 | 362 | if($SetIntuneDevicePrimaryUser -eq ""){ 363 | 364 | Write-Host "User"$User.displayName"set as Primary User for device '$($Device.deviceName)'..." -ForegroundColor Green 365 | 366 | } 367 | 368 | } 369 | 370 | else { 371 | #If the user is the same, then write to host that the primary user is already correct. 372 | Write-Host "The user '$($User.displayName)' is already the Primary User on the device..." -ForegroundColor Yellow 373 | 374 | } 375 | 376 | Write-Host 377 | 378 | } 379 | -------------------------------------------------------------------------------- /PrimaryUser/Set-PrimaryUserfromLastLogIn.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | .COPYRIGHT 4 | Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. 5 | See LICENSE in the project root for license information. 6 | 7 | #> 8 | 9 | #################################################### 10 | 11 | param 12 | ( 13 | [parameter(Mandatory=$false)] 14 | $DeviceName, 15 | [parameter(Mandatory=$false)] 16 | $UserPrincipalName 17 | 18 | ) 19 | 20 | #################################################### 21 | 22 | function Get-AuthToken { 23 | 24 | <# 25 | .SYNOPSIS 26 | This function is used to authenticate with the Graph API REST interface 27 | .DESCRIPTION 28 | The function authenticate with the Graph API Interface with the tenant name 29 | .EXAMPLE 30 | Get-AuthToken 31 | Authenticates you with the Graph API interface 32 | .NOTES 33 | NAME: Get-AuthToken 34 | #> 35 | 36 | [cmdletbinding()] 37 | 38 | param 39 | ( 40 | [Parameter(Mandatory=$true)] 41 | $User 42 | ) 43 | 44 | $userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $User 45 | 46 | $tenant = $userUpn.Host 47 | 48 | Write-Host "Checking for AzureAD module..." 49 | 50 | $AadModule = Get-Module -Name "AzureAD" -ListAvailable 51 | 52 | if ($AadModule -eq $null) { 53 | 54 | Write-Host "AzureAD PowerShell module not found, looking for AzureADPreview" 55 | $AadModule = Get-Module -Name "AzureADPreview" -ListAvailable 56 | 57 | } 58 | 59 | if ($AadModule -eq $null) { 60 | write-host 61 | write-host "AzureAD Powershell module not installed..." -f Red 62 | write-host "Install by running 'Install-Module AzureAD' or 'Install-Module AzureADPreview' from an elevated PowerShell prompt" -f Yellow 63 | write-host "Script can't continue..." -f Red 64 | write-host 65 | exit 66 | } 67 | 68 | # Getting path to ActiveDirectory Assemblies 69 | # If the module count is greater than 1 find the latest version 70 | 71 | if($AadModule.count -gt 1){ 72 | 73 | $Latest_Version = ($AadModule | select version | Sort-Object)[-1] 74 | 75 | $aadModule = $AadModule | ? { $_.version -eq $Latest_Version.version } 76 | 77 | # Checking if there are multiple versions of the same module found 78 | 79 | if($AadModule.count -gt 1){ 80 | 81 | $aadModule = $AadModule | select -Unique 82 | 83 | } 84 | 85 | $adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll" 86 | $adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll" 87 | 88 | } 89 | 90 | else { 91 | 92 | $adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll" 93 | $adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll" 94 | 95 | } 96 | 97 | [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null 98 | 99 | [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null 100 | 101 | $clientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547" 102 | 103 | $redirectUri = "urn:ietf:wg:oauth:2.0:oob" 104 | 105 | $resourceAppIdURI = "https://graph.microsoft.com" 106 | 107 | $authority = "https://login.microsoftonline.com/$Tenant" 108 | 109 | try { 110 | 111 | $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority 112 | 113 | # https://msdn.microsoft.com/en-us/library/azure/microsoft.identitymodel.clients.activedirectory.promptbehavior.aspx 114 | # Change the prompt behaviour to force credentials each time: Auto, Always, Never, RefreshSession 115 | 116 | $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto" 117 | 118 | $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId") 119 | 120 | $authResult = $authContext.AcquireTokenAsync($resourceAppIdURI,$clientId,$redirectUri,$platformParameters,$userId).Result 121 | 122 | # If the accesstoken is valid then create the authentication header 123 | 124 | if($authResult.AccessToken){ 125 | 126 | # Creating header for Authorization token 127 | 128 | $authHeader = @{ 129 | 'Content-Type'='application/json' 130 | 'Authorization'="Bearer " + $authResult.AccessToken 131 | 'ExpiresOn'=$authResult.ExpiresOn 132 | } 133 | 134 | return $authHeader 135 | 136 | } 137 | 138 | else { 139 | 140 | Write-Host 141 | Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red 142 | Write-Host 143 | break 144 | 145 | } 146 | 147 | } 148 | 149 | catch { 150 | 151 | write-host $_.Exception.Message -f Red 152 | write-host $_.Exception.ItemName -f Red 153 | write-host 154 | break 155 | 156 | } 157 | 158 | } 159 | 160 | #################################################### 161 | 162 | function Get-Win10IntuneManagedDevice { 163 | 164 | <# 165 | .SYNOPSIS 166 | This gets information on Intune managed devices 167 | .DESCRIPTION 168 | This gets information on Intune managed devices 169 | .EXAMPLE 170 | Get-Win10IntuneManagedDevice 171 | .NOTES 172 | NAME: Get-Win10IntuneManagedDevice 173 | #> 174 | 175 | [cmdletbinding()] 176 | 177 | param 178 | ( 179 | [parameter(Mandatory=$false)] 180 | [ValidateNotNullOrEmpty()] 181 | [string]$deviceName 182 | ) 183 | 184 | $graphApiVersion = "beta" 185 | 186 | try { 187 | 188 | if($deviceName){ 189 | 190 | $Resource = "deviceManagement/managedDevices?`$filter=deviceName eq '$deviceName'" 191 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)" 192 | 193 | (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).value 194 | 195 | } 196 | 197 | else { 198 | 199 | $Resource = "deviceManagement/managedDevices?`$filter=(((deviceType%20eq%20%27desktop%27)%20or%20(deviceType%20eq%20%27windowsRT%27)%20or%20(deviceType%20eq%20%27winEmbedded%27)%20or%20(deviceType%20eq%20%27surfaceHub%27)))" 200 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)" 201 | 202 | (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).value 203 | 204 | } 205 | 206 | } catch { 207 | $ex = $_.Exception 208 | $errorResponse = $ex.Response.GetResponseStream() 209 | $reader = New-Object System.IO.StreamReader($errorResponse) 210 | $reader.BaseStream.Position = 0 211 | $reader.DiscardBufferedData() 212 | $responseBody = $reader.ReadToEnd(); 213 | Write-Host "Response content:`n$responseBody" -f Red 214 | Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" 215 | throw "Get-IntuneManagedDevices error" 216 | } 217 | 218 | } 219 | 220 | #################################################### 221 | 222 | Function Get-AADUser(){ 223 | 224 | <# 225 | .SYNOPSIS 226 | This function is used to get AAD Users from the Graph API REST interface 227 | .DESCRIPTION 228 | The function connects to the Graph API Interface and gets any users registered with AAD 229 | .EXAMPLE 230 | Get-AADUser 231 | Returns all users registered with Azure AD 232 | .EXAMPLE 233 | Get-AADUser -userPrincipleName user@domain.com 234 | Returns specific user by UserPrincipalName registered with Azure AD 235 | .NOTES 236 | NAME: Get-AADUser 237 | #> 238 | 239 | [cmdletbinding()] 240 | 241 | param 242 | ( 243 | $userPrincipalName, 244 | $Property 245 | ) 246 | 247 | # Defining Variables 248 | $graphApiVersion = "v1.0" 249 | $User_resource = "users" 250 | 251 | try { 252 | 253 | if($userPrincipalName -eq "" -or $userPrincipalName -eq $null){ 254 | 255 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)" 256 | (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value 257 | 258 | } 259 | 260 | else { 261 | 262 | if($Property -eq "" -or $Property -eq $null){ 263 | 264 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)/$userPrincipalName" 265 | Write-Verbose $uri 266 | Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get 267 | 268 | } 269 | 270 | else { 271 | 272 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)/$userPrincipalName/$Property" 273 | Write-Verbose $uri 274 | (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value 275 | 276 | } 277 | 278 | } 279 | 280 | } 281 | 282 | catch { 283 | 284 | $ex = $_.Exception 285 | $errorResponse = $ex.Response.GetResponseStream() 286 | $reader = New-Object System.IO.StreamReader($errorResponse) 287 | $reader.BaseStream.Position = 0 288 | $reader.DiscardBufferedData() 289 | $responseBody = $reader.ReadToEnd(); 290 | Write-Host "Response content:`n$responseBody" -f Red 291 | Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" 292 | write-host 293 | break 294 | 295 | } 296 | 297 | } 298 | 299 | #################################################### 300 | 301 | function Get-IntuneDevicePrimaryUser { 302 | 303 | <# 304 | .SYNOPSIS 305 | This lists the Intune device primary user 306 | .DESCRIPTION 307 | This lists the Intune device primary user 308 | .EXAMPLE 309 | Get-IntuneDevicePrimaryUser 310 | .NOTES 311 | NAME: Get-IntuneDevicePrimaryUser 312 | #> 313 | 314 | [cmdletbinding()] 315 | 316 | param 317 | ( 318 | [Parameter(Mandatory=$true)] 319 | [string] $deviceId 320 | ) 321 | $graphApiVersion = "beta" 322 | $Resource = "deviceManagement/managedDevices" 323 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)" + "/" + $deviceId + "/users" 324 | 325 | try { 326 | 327 | $primaryUser = Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get 328 | 329 | return $primaryUser.value."id" 330 | 331 | } catch { 332 | $ex = $_.Exception 333 | $errorResponse = $ex.Response.GetResponseStream() 334 | $reader = New-Object System.IO.StreamReader($errorResponse) 335 | $reader.BaseStream.Position = 0 336 | $reader.DiscardBufferedData() 337 | $responseBody = $reader.ReadToEnd(); 338 | Write-Host "Response content:`n$responseBody" -f Red 339 | Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" 340 | throw "Get-IntuneDevicePrimaryUser error" 341 | } 342 | } 343 | 344 | #################################################### 345 | 346 | function Set-IntuneDevicePrimaryUser { 347 | 348 | <# 349 | .SYNOPSIS 350 | This updates the Intune device primary user 351 | .DESCRIPTION 352 | This updates the Intune device primary user 353 | .EXAMPLE 354 | Set-IntuneDevicePrimaryUser 355 | .NOTES 356 | NAME: Set-IntuneDevicePrimaryUser 357 | #> 358 | 359 | [cmdletbinding()] 360 | 361 | param 362 | ( 363 | [parameter(Mandatory=$true)] 364 | [ValidateNotNullOrEmpty()] 365 | $IntuneDeviceId, 366 | [parameter(Mandatory=$true)] 367 | [ValidateNotNullOrEmpty()] 368 | $userId 369 | ) 370 | $graphApiVersion = "beta" 371 | $Resource = "deviceManagement/managedDevices('$IntuneDeviceId')/users/`$ref" 372 | 373 | try { 374 | 375 | $uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)" 376 | 377 | $userUri = "https://graph.microsoft.com/$graphApiVersion/users/" + $userId 378 | 379 | $id = "@odata.id" 380 | $JSON = @{ $id="$userUri" } | ConvertTo-Json -Compress 381 | 382 | Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON -ContentType "application/json" 383 | 384 | } catch { 385 | $ex = $_.Exception 386 | $errorResponse = $ex.Response.GetResponseStream() 387 | $reader = New-Object System.IO.StreamReader($errorResponse) 388 | $reader.BaseStream.Position = 0 389 | $reader.DiscardBufferedData() 390 | $responseBody = $reader.ReadToEnd(); 391 | Write-Host "Response content:`n$responseBody" -f Red 392 | Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" 393 | throw "Set-IntuneDevicePrimaryUser error" 394 | } 395 | 396 | } 397 | 398 | #################################################### 399 | 400 | #region Authentication 401 | 402 | write-host 403 | 404 | # Checking if authToken exists before running authentication 405 | if($global:authToken){ 406 | 407 | # Setting DateTime to Universal time to work in all timezones 408 | $DateTime = (Get-Date).ToUniversalTime() 409 | 410 | # If the authToken exists checking when it expires 411 | $TokenExpires = ($authToken.ExpiresOn.datetime - $DateTime).Minutes 412 | 413 | if($TokenExpires -le 0){ 414 | 415 | write-host "Authentication Token expired" $TokenExpires "minutes ago" -ForegroundColor Yellow 416 | write-host 417 | 418 | # Defining User Principal Name if not present 419 | 420 | if($User -eq $null -or $User -eq ""){ 421 | $User = Read-Host -Prompt "Please specify your user principal name for Azure Authentication" 422 | Write-Host 423 | } 424 | 425 | $global:authToken = Get-AuthToken -User $User 426 | } 427 | } 428 | 429 | # Authentication doesn't exist, calling Get-AuthToken function 430 | 431 | else { 432 | 433 | if($User -eq $null -or $User -eq "") { 434 | $User = Read-Host -Prompt "Please specify your user principal name for Azure Authentication" 435 | Write-Host 436 | } 437 | 438 | # Getting the authorization token 439 | $global:authToken = Get-AuthToken -User $User 440 | } 441 | 442 | #endregion 443 | 444 | #################################################### 445 | 446 | #Get All Windows 10 Intune Managed Devices for the Tenant 447 | $Devices = Get-Win10IntuneManagedDevice 448 | 449 | Foreach ($Device in $Devices){ 450 | 451 | Write-Host "Device name:" $device."deviceName" -ForegroundColor Cyan 452 | $IntuneDevicePrimaryUser = Get-IntuneDevicePrimaryUser -deviceId $Device.id 453 | 454 | #Check if there is a Primary user set on the device already 455 | if($IntuneDevicePrimaryUser -eq $null){ 456 | 457 | Write-Host "No Intune Primary User Id set for Intune Managed Device" $Device."deviceName" -f Red 458 | 459 | } 460 | 461 | else { 462 | $PrimaryAADUser = Get-AADUser -userPrincipalName $IntuneDevicePrimaryUser 463 | Write-Host "Intune Device Primary User:" $PrimaryAADUser.displayName 464 | 465 | } 466 | 467 | #Get the objectID of the last logged in user for the device, which is the last object in the list of usersLoggedOn 468 | $LastLoggedInUser = ($Device.usersLoggedOn[-1]).userId 469 | 470 | #Using the objectID, get the user from the Microsoft Graph for logging purposes 471 | $User = Get-AADUser -userPrincipalName $LastLoggedInUser 472 | 473 | #Check if the current primary user of the device is the same as the last logged in user 474 | if($IntuneDevicePrimaryUser -notmatch $User.id){ 475 | 476 | #If the user does not match, then set the last logged in user as the new Primary User 477 | $SetIntuneDevicePrimaryUser = Set-IntuneDevicePrimaryUser -IntuneDeviceId $Device.id -userId $User.id 478 | 479 | if($SetIntuneDevicePrimaryUser -eq ""){ 480 | 481 | Write-Host "User"$User.displayName"set as Primary User for device '$($Device.deviceName)'..." -ForegroundColor Green 482 | 483 | } 484 | 485 | } 486 | 487 | else { 488 | #If the user is the same, then write to host that the primary user is already correct. 489 | Write-Host "The user '$($User.displayName)' is already the Primary User on the device..." -ForegroundColor Yellow 490 | 491 | } 492 | 493 | Write-Host 494 | 495 | } 496 | --------------------------------------------------------------------------------