Functions/Remove-AadDevices.ps1


function Remove-AadDevices {
    [CmdletBinding()]
    param (
        [Parameter()] [string] $Filter,
        [Parameter()] [int] $AgeInDays = 90,
        [Parameter()] [switch] $DuplicateDevicesOnly
    )

    # $PSBoundParameters


    if (-not(Get-MgContext)) {
        throw "MgGraph not connected, please connect with Connect-MgGraph"
    }

    if ((Get-MgProfile).Name -ne "beta") {
        Select-MgProfile beta
    }


    $Params = @{
        All = $true
    }
    if ($Filter) {
        $Params.Add('Filter', $Filter)
    }
    $Params

    $AadDevices = Get-MgDevice @Params

    if (!($AadDevices)) {
        throw "No devices found"
    }

    # $AadDevices | Select-Object Id, DeviceId, DeviceOwnership, DisplayName, AccountEnabled, IsCompliant, ManagementType, Manufacturer, Model, ProfileType, RegistrationDateTime, ApproximateLastSignInDateTime | fl
    $AadDevices2 = @()

    if ($DuplicateDevicesOnly) {
        $AadDevices | ForEach-Object {
            if (($AadDevices | Where-Object DisplayName -EQ $_.DisplayName).count -gt 1) {
                $AadDevices2 += $_
            }
        }
    } else {
        $AadDevices2 = $AadDevices
    }


    $AadDevices2 | Select-Object Id, DisplayName, ApproximateLastSignInDateTime | Format-Table
    # $AadDevices2 | Select-Object * | Format-List

    # $AadDevices2 | Export-Excel

}