Import-Module Microsoft.Graph.Authentication

Import-Module Microsoft.Graph.Identity.DirectoryManagement

Connect-MgGraph -Scopes “Directory.AccessAsUser.All”

Connect-AzureAD

Select-MgProfile Beta

#Install-Module Microsoft.Graph

#Install-PackageProvider -Name NuGet -Force

[array]$Devices=$null

$Dev=Import-Csv -Path C:\Temp\list.csv #CSV path

$Devices1=$Dev.DeviceId

ForEach ($ids in $Devices1) {

[array]$Devices+=Get-MgDevice -Filter “DeviceId eq ‘$($ids)’” -All

}

ForEach ($Device in $Devices) {

If ($Device.PhysicalIds.count -gt 0) {

Foreach ($X in $Device.PhysicalIds) {

If ($X.SubString(0,10) -eq “[USER-GID]”) { $UserGuid = $X } }

$UserId = $UserGuid.substring(11,36)

If ($UserId) {

[array]$User = Get-MgUser -UserId $UserId -ErrorAction SilentlyContinue }

If ($User) {

Write-Host (“Device {0} owned by {1}” -f $Device.DisplayName, $User.DisplayName)

$Attributes = @{

“extensionAttributes” = @{

“extensionAttribute13” = $User.extensionAttribute13 }

} | ConvertTo-Json

Update-MgDevice -DeviceId $Device.Id -BodyParameter $Attributes

}

Else { Write-Host (“Device {0} owned by unknown user {1}” -f $Device.DisplayName, $UserId ) }

}

}

Disconnect-MgGraph

#device ID and user pulled from .csv is correct but just not able to pull extensionAttribute as defined in the script . but if i change $User.extensionAttribute13 to “some value” it shows up in azure portal user devices, why am i not able to pull extension attribute from the user ?

5 Spice ups

There is a dedicated sdk cmdlet for extensions:
Get-MgUserExtension

Example here:

2 Spice ups

Please use the </> button in the toolbar to post your code in a format that is easier to read.

I can’t answer your main question, but I do have a suggestions for your code.

The += operator is inefficient for creating arrays in a loop, because arrays in Powershell have a fixed length. Whenever you append data to an array, Powershell creates a new array that is longer than the existing array and then copies the data from the first array to the second. Instead of this:

ForEach ($ids in $Devices1) {
    [array]$Devices+=Get-MgDevice -Filter "DeviceId eq '$($ids)'" -All
}

Do this:

$Devices = ForEach ($ids in $Devices1) {
    Get-MgDevice -Filter "DeviceId eq '$($ids)'" -All
}
4 Spice ups

Hi all i was able to complete the script and its works like champ now !! extensionAttribute value was an object ID and i was trying to write host a string, later converted the ObjectID to string and it resolved the issue