Search code examples
azurepowershellmicrosoft-graph-apimicrosoft-entra-id

PowerShell select-object does not work with "Invoke-MgGraphRequest" but it worked with Invoke-RestMethod


In the past, I would get all Intune devices with Invoke-RestMethod and do select-object on returned data. Now that I have to use Invoke-MgGraphRequest, the returned array does not like select-object. The property value gets returned by "Array.property" name but not by Select-Object

is there a way to use select-object here?

In the example below :

$Devices | select deviceName   # Does not work #
$Devices.devicename            # it works #
$uri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices?`$Filter= (deviceType eq 'desktop') or (deviceType eq 'windowsRT') or (deviceType eq 'winEmbedded')"  #30 min to run - 136 trys
$DevicesResponse = (Invoke-MgGraphRequest -Uri $uri -Method Get)
$Devices = $DevicesResponse.value
$DevicesNextLink = $DevicesResponse.'@odata.nextLink'
$i = 0
while ($DevicesNextLink -ne $null) {    
    Write-Host $i -BackgroundColor DarkGreen
    $DevicesResponse = (Invoke-MgGraphRequest -Uri $DevicesNextLink -Method Get)
    $DevicesNextLink = $DevicesResponse.'@odata.nextLink'
    $Devices += $DevicesResponse.value
    $i++
    $Devices.count
    $date = Get-Date
    $date.DateTime
}

Solution

  • Invoke-MgGraphRequest outputs hashtable by default, in PowerShell 5.1 Select-Object is not able to handle them from pipeline so the solution is as simple as -OutputType psobject to have the cmdlet output custom objects instead. Your paging logic also can be simplified:

    $uri = "https://longurihere...."
    $i = 0
    $devices = do {
        Write-Host $i -BackgroundColor DarkGreen
        $response = Invoke-MgGraphRequest GET $uri -OutputType psobject
        $uri = $response.'@odata.nextLink'
        if ($response.value) {
            $response.value
        }
        $i++
        (Get-Date).DateTime | Write-Host
    }
    while ($uri)
    
    $Devices | Select-Object deviceName # should work