ds-intune.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 |
<#
.COPYRIGHT Portions of this are derived from Microsoft content on GitHub at the following URL: https://github.com/microsoftgraph/powershell-intune-samples/blob/master/ManagedDevices/ManagedDevices_Apps_Get.ps1 Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. See LICENSE in the project root for license information. #> #region Microsoft GitHub sample code $graphApiVersion = "beta" function Get-AuthToken { <# .SYNOPSIS This function is used to authenticate with the Graph API REST interface .DESCRIPTION The function authenticate with the Graph API Interface with the tenant name .PARAMETER User UserName for cloud services access .EXAMPLE Get-AuthToken -User "john.doe@contoso.com" Authenticates user with the Graph API interface .NOTES NAME: Get-AuthToken #> [cmdletbinding()] param ( [parameter(Mandatory)] $User ) $userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $User $tenant = $userUpn.Host Write-Host "Checking for AzureAD module..." $AadModule = Get-Module -Name "AzureAD" -ListAvailable if ($null -eq $AadModule) { Write-Host "AzureAD PowerShell module not found, looking for AzureADPreview" $AadModule = Get-Module -Name "AzureADPreview" -ListAvailable } if ($null -eq $AadModule) { Write-Host Write-Host "AzureAD Powershell module not installed..." -f Red Write-Host "Install by running 'Install-Module AzureAD' or 'Install-Module AzureADPreview' from an elevated PowerShell prompt" -f Yellow Write-Host "Script can't continue..." -f Red Write-Host exit } # Getting path to ActiveDirectory Assemblies # If the module count is greater than 1 find the latest version if ($AadModule.count -gt 1){ $Latest_Version = ($AadModule | Select-Object version | Sort-Object)[-1] $aadModule = $AadModule | Where-Object { $_.version -eq $Latest_Version.version } # Checking if there are multiple versions of the same module found if($AadModule.count -gt 1){ $aadModule = $AadModule | Select-Object -Unique } $adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll" $adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll" } else { $adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll" $adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll" } [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null $clientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547" $redirectUri = "urn:ietf:wg:oauth:2.0:oob" $resourceAppIdURI = "https://graph.microsoft.com" $authority = "https://login.microsoftonline.com/$Tenant" try { $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority # https://msdn.microsoft.com/en-us/library/azure/microsoft.identitymodel.clients.activedirectory.promptbehavior.aspx # Change the prompt behaviour to force credentials each time: Auto, Always, Never, RefreshSession $platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto" $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId") $authResult = $authContext.AcquireTokenAsync($resourceAppIdURI,$clientId,$redirectUri,$platformParameters,$userId).Result # If the accesstoken is valid then create the authentication header if ($authResult.AccessToken){ # Creating header for Authorization token $authHeader = @{ 'Content-Type'='application/json' 'Authorization'="Bearer " + $authResult.AccessToken 'ExpiresOn'=$authResult.ExpiresOn } return $authHeader } else { Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red break } } catch { Write-Error $_.Exception.Message Write-Error $_.Exception.ItemName break } } function Get-DsIntuneAuth { <# .SYNOPSIS Returns authentication token object .PARAMETER UserName UserName for cloud services access .EXAMPLE Get-DsIntuneAuth -UserName "john.doe@contoso.com" .NOTES Name: Get-DsIntuneAuth #> [CmdletBinding()] param ( [parameter(Mandatory)][string] $UserName ) # Checking if authToken exists before running authentication if ($global:authToken) { # Setting DateTime to Universal time to work in all timezones $DateTime = (Get-Date).ToUniversalTime() # If the authToken exists checking when it expires $TokenExpires = ($authToken.ExpiresOn.datetime - $DateTime).Minutes if ($TokenExpires -le 0){ Write-Host "Authentication Token expired" $TokenExpires "minutes ago" -ForegroundColor Yellow # Defining Azure AD tenant name, this is the name of your Azure Active Directory (do not use the verified domain name) $global:authToken = Get-AuthToken -User $UserName } } else { # Authentication doesn't exist, calling Get-AuthToken function $global:authToken = Get-AuthToken -User $UserName } } Function Get-DsIntuneAzureADUser() { <# .SYNOPSIS This function is used to get AAD Users from the Graph API REST interface .DESCRIPTION The function connects to the Graph API Interface and gets any users registered with AAD .EXAMPLE Get-DsIntuneAzureADUser Returns all users registered with Azure AD .EXAMPLE Get-DsIntuneAzureADUser -userPrincipleName user@domain.com Returns specific user by UserPrincipalName registered with Azure AD .NOTES NAME: Get-DsIntuneAzureADUser .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneAzureADUser.md #> [cmdletbinding()] param ( [parameter()][string] $userPrincipalName, [parameter()][string] $Property ) $User_resource = "users" try { if ([string]::IsNullOrEmpty($userPrincipalName)) { $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)" (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value } else { if ([string]::IsNullOrEmpty($Property)) { $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)/$userPrincipalName" Write-Verbose $uri Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get } else { $uri = "https://graph.microsoft.com/$graphApiVersion/$($User_resource)/$userPrincipalName/$Property" Write-Verbose $uri (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value } } } catch { $ex = $_.Exception $errorResponse = $ex.Response.GetResponseStream() $reader = New-Object System.IO.StreamReader($errorResponse) $reader.BaseStream.Position = 0 $reader.DiscardBufferedData() $responseBody = $reader.ReadToEnd(); Write-Host "Response content:`n$responseBody" -f Red Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" #Write-Host break } } function Get-DsIntuneAzureADDevices { <# .SYNOPSIS Return AzureAD device accounts .DESCRIPTION Return all AzureAD tenant device accounts .EXAMPLE Get-DsIntuneAzureADDevices .NOTES Name: Get-DsIntuneAzureADDevices .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneAzureADDevices.md #> [CmdletBinding()] param() if (!$AADCred) { $Global:AADCred = Connect-AzureAD } Write-Verbose "requesting devices from Azure AD tenant" $aadcomps = Get-AzureADDevice -All $True Write-Verbose "returned $($aadcomps.Count) devices from Azure AD" $aadcomps | Foreach-Object { $llogin = $_.ApproximateLastLogonTimeStamp if (![string]::IsNullOrEmpty($llogin)) { $xdaysOld = (New-TimeSpan -Start $([datetime]$llogin) -End (Get-Date)).Days } else { $xdaysOld = $null } if (![string]::IsNullOrEmpty($_.LastDirSyncTime)) { $xSyncDays = (New-TimeSpan -Start $([datetime]$_.LastDirSyncTime) -End (Get-Date)).Days } else { $xSyncDays = $null } [pscustomobject]@{ Name = $_.DisplayName DeviceId = $_.DeviceId ObjectId = $_.ObjectId Enabled = $_.AccountEnabled OSName = $_.DeviceOSType OSVersion = $_.DeviceOSVersion TrustType = $_.DeviceTrustType LastLogon = $_.ApproximateLastLogonTimeStamp LastLogonDays = $xdaysOld IsCompliant = $($_.IsCompliant -eq $True) IsManaged = $($_.IsManaged -eq $True) DirSyncEnabled = $($_.DirSyncEnabled -eq $True) LastDirSync = $_.LastDirSyncTime LastSyncDays = $xSyncDays ProfileType = $_.ProfileType } } } Function Get-MsGraphData($Path) { <# .SYNOPSIS Returns MS Graph data from (beta) REST API query .PARAMETER Path REST API URI path suffix .NOTES This function was derived from https://www.dowst.dev/search-intune-for-devices-with-application-installed/ (Thanks to Matt Dowst) #> $FullUri = "https://graph.microsoft.com/$graphApiVersion/$Path" [System.Collections.Generic.List[PSObject]]$Collection = @() $NextLink = $FullUri do { $Result = Invoke-RestMethod -Method Get -Uri $NextLink -Headers $AuthHeader if ($Result.'@odata.count') { $Result.value | ForEach-Object{$Collection.Add($_)} } else { $Collection.Add($Result) } $NextLink = $Result.'@odata.nextLink' } while ($NextLink) return $Collection } Function Get-ManagedDevices(){ <# .SYNOPSIS This function is used to get Intune Managed Devices from the Graph API REST interface .DESCRIPTION The function connects to the Graph API Interface and gets any Intune Managed Device .PARAMETER IncludeEAS Switch to include EAS devices (not included by default) .PARAMETER ExcludeMDM Switch to exclude MDM devices (not excluded by default) .EXAMPLE Get-ManagedDevices Returns all managed devices but excludes EAS devices registered within the Intune Service .EXAMPLE Get-ManagedDevices -IncludeEAS Returns all managed devices including EAS devices registered within the Intune Service .NOTES NAME: Get-ManagedDevices .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-ManagedDevices.md #> [cmdletbinding()] param ( [parameter(Mandatory)][string] $UserName, [parameter()][switch] $IncludeEAS, [parameter()][switch] $ExcludeMDM ) #$graphApiVersion = "beta" $Resource = "deviceManagement/managedDevices" try { Get-DsIntuneAuth -UserName $UserName $Count_Params = 0 if ($IncludeEAS.IsPresent){ $Count_Params++ } if ($ExcludeMDM.IsPresent){ $Count_Params++ } if ($Count_Params -gt 1) { Write-Warning "Multiple parameters set, specify a single parameter -IncludeEAS, -ExcludeMDM or no parameter against the function" #Write-Host break } elseif ($IncludeEAS) { $uri = "https://graph.microsoft.com/$graphApiVersion/$Resource" } elseif ($ExcludeMDM) { $uri = "https://graph.microsoft.com/$graphApiVersion/$Resource`?`$filter=managementAgent eq 'eas'" } else { $uri = "https://graph.microsoft.com/$graphApiVersion/$Resource`?`$filter=managementAgent eq 'mdm' and managementAgent eq 'easmdm'" Write-Warning "EAS Devices are excluded by default, please use -IncludeEAS if you want to include those devices" #Write-Host } $response = (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get) $Devices = $response.Value $DevicesNextLink = $response."@odata.nextLink" while ($DevicesNextLink) { $response = (Invoke-RestMethod -Uri $DevicesNextLink -Headers $authToken -Method Get) $DevicesNextLink = $response."@odata.nextLink" $Devices += $response.value } $Devices } catch { $ex = $_.Exception $errorResponse = $ex.Response.GetResponseStream() $reader = New-Object System.IO.StreamReader($errorResponse) $reader.BaseStream.Position = 0 $reader.DiscardBufferedData() $responseBody = $reader.ReadToEnd(); Write-Warning "Response content:`n$responseBody" Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" Write-Host break } } #endregion function Get-DsIntuneDevices { <# .SYNOPSIS Returns dataset of Intune-managed devices with inventoried apps .DESCRIPTION Returns dataset of Intune-managed devices with inventoried apps .PARAMETER UserName UserPrincipalName for authentication request .PARAMETER ShowProgress Display progress as data is exported (default is silent / no progress shown) .PARAMETER Detailed Optional expanded list of device properties which includes: * DeviceName, DeviceID, Manufacturer, Model, MemoryGB, DiskSizeGB, FreeSpaceGB, EthernetMAC, SerialNumber, OSName, OSVersion, Ownership, Category, LastSyncTime, UserName, Apps * The default return property set: DeviceName, DeviceID, OSName, OSVersion, LastSyncTime, UserName, Apps * Note that for either case, Apps will be set to $null if parameter -NoApps is used .PARAMETER NoApps Exclude installed Applications data from return dataset This reduces overall query time significantly! .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" Returns results of online request to variable $devices .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" -ShowProgress Returns results of online request to variable $devices while displaying concurrent progress .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" -Detailed -NoApps Returns detailed results of online request to variable $devices without installed applications data .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" -NoApps Returns summary results of online request to variable $devices without installed applications data This is the fastest query option of all the parameter options .NOTES NAME: Get-DsIntuneDevices .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneDevices.md #> [CmdletBinding()] param( [parameter(Mandatory)][string] $UserName, [parameter()][switch] $ShowProgress, [parameter()][switch] $Detailed, [parameter()][switch] $NoApps ) #if ($UserName) { Get-DsIntuneAuth -UserName $UserName } else { Get-DsIntuneAuth } $Devices = Get-ManagedDevices -UserName $UserName Write-Host "returned $($Devices.Count) managed devices" if ($Devices) { if ($Detailed) { Write-Host "getting detailed device properties (this may take a few minutes)..." } else { Write-Host "getting device properties..." } $dx = 1 $dcount = $Devices.Count foreach ($Device in $Devices){ if ($ShowProgress) { Write-Progress -Activity "Found $dcount" -Status "$dx of $dcount" -PercentComplete $(($dx/$dcount)*100) -id 1 } $DeviceID = $Device.id $uri = "https://graph.microsoft.com/$graphApiVersion/deviceManagement/manageddevices('$DeviceID')?`$expand=detectedApps" if (!$NoApps) { $DetectedApps = (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).detectedApps } $dx++ $LastSync = $Device.lastSyncDateTime $SyncDays = (New-TimeSpan -Start $LastSync -End (Get-Date)).Days if ($Detailed) { $compliant = $($Device.complianceState -eq $True) $disksize = [math]::Round(($Device.totalStorageSpaceInBytes / 1GB),2) $freespace = [math]::Round(($Device.freeStorageSpaceInBytes / 1GB),2) $mem = [math]::Round(($Device.physicalMemoryInBytes / 1GB),2) [pscustomobject]@{ DeviceName = $Device.DeviceName DeviceID = $DeviceID Manufacturer = $Device.manufacturer Model = $Device.model UserName = $Device.userDisplayName EthernetMAC = $Device.ethernetMacAddress WiFiMAC = $Device.WiFiMacAddress MemoryGB = $mem DiskSizeGB = $disksize FreeSpaceGB = $freespace SerialNumber = $Device.serialNumber OSName = $Device.operatingSystem OSVersion = $Device.osVersion Ownership = $Device.ownerType Category = $Device.deviceCategoryDisplayName EnrollDate = $Device.enrolledDateTime LastSyncTime = $LastSync LastSyncDays = $SyncDays Compliant = $compliant AutoPilot = $Device.autopilotEnrolled Apps = $DetectedApps } } else { [pscustomobject]@{ DeviceName = $Device.DeviceName DeviceID = $DeviceID UserName = $Device.userDisplayName OSName = $Device.operatingSystem OSVersion = $Device.osVersion LastSyncTime = $LastSync LastSyncDays = $SyncDays Apps = $DetectedApps } } } } else { Write-Host "No Intune Managed Devices found..." -f green Write-Host } } function Get-DsIntuneDevicesRaw { <# .SYNOPSIS Returns raw data for all Intune devices .DESCRIPTION Returns raw data for all Intune devices .EXAMPLE $allDevices = Get-DsIntuneDevicesRaw .NOTES NAME: Get-DsIntuneDevicesRaw Alias for Get-ManagedDevices() .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneDevicesRaw.md #> [CmdletBinding()] param () Get-ManagedDevices } function Get-DsIntuneDeviceSummary { <# .SYNOPSIS Returns Summary by Property Set .DESCRIPTION Returns grouped data by property set .PARAMETER Property Name of device property to group dataset on. Default is OSName .PARAMETER DataSet Devices dataset returned from Get-DsIntuneDevices .PARAMETER UserName Required for invoked query if DataSet is $null .PARAMETER ShowProgress Show progress indicator while querying dataset .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" Get-DsIntuneDeviceSummary -DataSet $devices -Property Model -ShowProgress Query against data returned from direct query and saved to $devices .EXAMPLE Get-DsIntuneDeviceSummary -Property Model -UserName "john.doe@contoso.com" -ShowProgress Query data directly from Intune graph source .NOTES Name: Get-DsIntuneDeviceSummary .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneDeviceSummary.md #> [CmdletBinding()] param ( [parameter()][ValidateSet('OSName','Model','Manufacturer','ComplianceState','AutoPilotEnrolled','Ownership')] $Property = 'OSName', [parameter()] $DataSet, [parameter()][string] $UserName, [parameter()][switch] $ShowProgress ) if ($null -eq $DataSet) { $DataSet = Get-DsIntuneDevices -UserName $UserName -Detailed -ShowProgress:$ShowProgress -NoApps } $DataSet | Where-Object {![string]::IsNullOrEmpty($_."$Property")} | Select-Object DeviceName,$Property | Sort-Object DeviceName -Unique | Group-Object $Property | Select-Object Count,Name } function Get-DsIntuneStaleDevices { <# .SYNOPSIS Returns devices which have not synchronized within the last N (-Days) .DESCRIPTION Returns Intune device accounts which have not synchronized within the last <N> days as specified by -Days .PARAMETER DataSet Data returned from Get-DsIntuneDeviceData() .PARAMETER Days Number of days to allow, from 1 to 1000 (default is 30) .PARAMETER Detailed Returns detailed property set for each device (see Get-DsIntuneDeviceData) if -DataSet is $null .PARAMETER ShowProgress Displays progress during query if -DataSet is $null .EXAMPLE Get-DsIntuneStaleDevices -DataSet $devices Returns devices which have not synchronized with AzureAD in the last 30 days .EXAMPLE Get-DsIntuneStaleDevices -DataSet $devices -Detailed -Days 60 Returns devices with detailed properties which have not synchronized with AzureAD in the last 60 days .NOTES NAME: Get-DsIntuneStaleDevices .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneStaleDevices.md #> [CmdletBinding()] param ( [parameter()] $DataSet, [parameter()][string] $UserName, [parameter()][ValidateRange(1,1000)][int] $Days = 30, [parameter()][switch] $Detailed, [parameter()][switch] $ShowProgress ) try { if (!$DataSet) { Write-Host "querying Intune devices" -ForegroundColor Cyan $DataSet = Get-DsIntuneDevices -UserName $UserName -ShowProgress:$ShowProgress -Detailed:$Detailed -NoApps } else { Write-Verbose "re-querying $($DataSet.Count) devices from existing dataset" } $result = $DataSet | Where-Object {($null -eq $_.LastSyncTime) -or $(New-TimeSpan -Start $_.LastSyncTime -End (Get-Date)).Days -gt $Days} } catch { Write-Error $_.Exception.Message } finally { $result } } function Get-DsIntuneInstalledApps ($DataSet) { <# .SYNOPSIS Returns App inventory data from Intune Device data set .DESCRIPTION Returns App inventory data from Intune Device data set .PARAMETER DataSet Data returned from Get-DsIntuneDevices() .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" $applist = Get-DsIntuneDeviceApps -DataSet $devices .NOTES NAME: Get-DsIntuneInstalledApps .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneInstalledApps.md #> if (!$DataSet) { Write-Warning "device accounts dataset from Get-DsIntuneDevices required" break } $badnames = ('. .','. . .','..','...') foreach ($row in $Dataset) { $devicename = $row.DeviceName if ($null -ne $row.Apps) { $apps = $row.Apps foreach ($app in $apps) { $displayName = $($app.displayName).ToString().Trim() if (![string]::IsNullOrEmpty($displayName)) { if ($displayName -notin $badnames) { if ($($app.Id).Length -gt 36) { $ptype = 'WindowsStore' } elseif ($($app.Id).Length -eq 36) { $ptype = 'Win32' } else { $ptype = 'Other' } [pscustomobject]@{ ProductName = $displayName ProductVersion = $($app.version).ToString().Trim() ProductCode = $app.Id ProductType = $ptype DeviceName = $devicename } } } } } } } function Get-DsIntuneDevicesWithApp { <# .SYNOPSIS Returns Intune managed devices having a specified App installed .DESCRIPTION Returns Intune managed devices having a specified App installed .PARAMETER AppDataSet Applications dataset returned from Get-DsIntuneDeviceApps(). If not provided, Devices are queried automatically, which will incur additional time. .PARAMETER Application Name, or wildcard name, of App to search for .PARAMETER UserName UserPrincipalName for authentication request .PARAMETER ShowProgress Display progress during execution (default is silent / no progress shown) .EXAMPLE Get-DsIntuneDevicesWithApp -Application "*Putty*" -UserName "john.doe@contoso.com" Returns list of Intune-managed devices which have any app name containing "Putty" installed .EXAMPLE Get-DsIntuneDevicesWithApp -Application "*Putty*" -UserName "john.doe@contoso.com" -ShowProgress Returns list of Intune-managed devices which have any apps name containing "Putty" installed, and displays progress during execution .NOTES NAME: Get-DsIntuneDevicesWithApp This function was derived almost entirely from https://www.dowst.dev/search-intune-for-devices-with-application-installed/ (Thanks to Matt Dowst) .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneDevicesWithApp.md #> [CmdletBinding()] param ( [parameter()] $AppDataSet, [parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Application, [parameter()][string] $Version, [parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Username, [parameter()][switch] $ShowProgress ) Write-Verbose "Getting authentication token" $AuthHeader = Get-AuthToken -User $Username Write-Verbose "getting all devices in Intune" $AllDevices = Get-MsGraphData "deviceManagement/managedDevices" # Get detected app for each device and check for app name [System.Collections.Generic.List[PSObject]]$FoundApp = @() $wp = 1 Write-Verbose "querying devices for $Application $Version" foreach ($Device in $AllDevices) { if ($ShowProgress) { Write-Progress -Activity "Found $($FoundApp.count)" -Status "$wp of $($AllDevices.count)" -PercentComplete $(($wp/$($AllDevices.count))*100) -id 1 } $AppData = Get-MsGraphData "deviceManagement/managedDevices/$($Device.id)?`$expand=detectedApps" $DetectedApp = $AppData.detectedApps | Where-Object {$_.displayname -like $Application} if (![string]::IsNullOrEmpty($Version)) { $DetectedApp = $DetectedApp | Where-Object { $_.ProductVersion -eq $Version } } if ($DetectedApp) { $DetectedApp | Select-Object @{l='DeviceName';e={$Device.DeviceName}}, @{l='Application';e={$_.displayname}}, Version, SizeInByte, @{l='LastSyncDateTime';e={$Device.lastSyncDateTime}}, @{l='DeviceId';e={$Device.id}} | Foreach-Object { $FoundApp.Add($_) } } $wp++ } if ($ShowProgress) { Write-Progress -Activity "Done" -Id 1 -Completed } $FoundApp } function Get-DsIntuneInstalledAppCounts { <# .SYNOPSIS Return Applications grouped and sorted by Installation Counts .DESCRIPTION Return Applications grouped and sorted by Installation Counts in descending order .PARAMETER AppDataSet Applications dataset returned from Get-DsIntuneInstalledApps() .PARAMETER RowCount Limit to first (N) rows (default is 0 / returns all rows) .EXAMPLE $apps = Get-DsIntuneInstalledApps -DataSet $devices $top20 = Get-DsIntuneInstalledAppCounts -AppDataSet $apps -RowCount 20 .NOTES NAME: Get-DsIntuneInstalledAppCounts .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Get-DsIntuneInstalledAppCounts.md #> param ( [parameter()] $AppDataSet, [parameter()][int] $RowCount = 0 ) try { $result = $AppDataSet | Group-Object -Property ProductName,ProductVersion | Select-Object Count,Name | Sort-Object Count -Descending if ($RowCount -gt 0) { $result | Select-Object -First $RowCount } else { $result } } catch { Write-Error $_.Exception.Message } } function Export-DsIntuneInventory { <# .SYNOPSIS Export Intune Device Applications Inventory to Excel Workbook .DESCRIPTION Export Intune Device Applications Inventory to Excel Workbook .PARAMETER DeviceData Device data returned from Get-DsIntuneDeviceData(). If not provided, Get-DsIntuneDeviceData() is invoked automatically. Passing Device data to -DeviceData can save significant processing time. .PARAMETER Title Title used for prefix of XLSX filename .PARAMETER UserName UserPrincipalName for authentication .PARAMETER Overwrite Replace output file it exists .PARAMETER DaysOld Filter stale accounts by specified number of days (range 10 to 1000, default = 180) .PARAMETER Show Open workbook in Excel when completed (requires Excel on host machine) .PARAMETER Distinct Filter DeviceName+AppName only to remove duplicates arising from different versions .PARAMETER DeviceOS Filter devices and derivative datasets to specified OS. Options include: Windows, iOS, Android, or All. Default is 'All' .EXAMPLE Export-DsIntuneInventory -Title "Contoso" -UserName "john.doe@contoso.com" -Overwrite Queries all Intune devices and applications to generate output file .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" $apps = Get-DsIntuneInstalledApps -DataSet $devices Export-DsIntuneInventory -DeviceData $devices -Title "Contoso" -UserName "john.doe@contoso.com" -Overwrite -Show Processes existing data ($devices) to generate output file with "Contoso" in the filename, and display the results in Excel when finished .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" $apps = Get-DsIntuneInstalledApps -DataSet $devices Export-DsIntuneInventory -DeviceData $devices -Title "Contoso" -UserName "john.doe@contoso.com" -Overwrite -Show -Distinct Processes existing data ($devices) to generate output file with "Contoso" in the filename, and display the unique App results in Excel when finished .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" | Where-Object {$_.OSName -eq 'Windows'} $apps = Get-DsIntuneInstalledApps -DataSet $devices Export-DsIntuneInventory -DeviceData $devices -Title "Contoso" -UserName "john.doe@contoso.com" -Overwrite -Show -Distinct Processes existing data ($devices) for only Windows devices, to generate output file with "Contoso" in the filename, and display the unique App results in Excel when finished .EXAMPLE $devices = Get-DsIntuneDevices -UserName "john.doe@contoso.com" -DeviceOS 'Windows' $apps = Get-DsIntuneInstalledApps -DataSet $devices Export-DsIntuneInventory -DeviceData $devices -Title "Contoso" -UserName "john.doe@contoso.com" -Overwrite -Show -Distinct Processes existing data ($devices) for only Windows devices, to generate output file with "Contoso" in the filename, and display the unique App results in Excel when finished .NOTES NAME: Export-DsIntuneInventory Requires PS module ImportExcel .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Export-DsIntuneInventory.md #> [CmdletBinding()] param ( [parameter()] $DeviceData, [parameter()][string] $OutputFolder = "$($env:USERPROFILE)\Documents", [parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Title, [parameter()][ValidateNotNullOrEmpty()][string] $UserName, [parameter()][switch] $Overwrite, [parameter()][switch] $Distinct, [parameter()][int][ValidateRange(10,1000)] $DaysOld = 180, [parameter()][string][ValidateSet('All','Windows','Android','iOS')] $DeviceOS = 'All', [parameter()][switch] $Show ) if (!(Get-Module ImportExcel -ListAvailable)) { Write-Warning "This function requires the PowerShell module ImportExcel, which is not installed." break } if ($null -eq $DeviceData) { if ([string]::IsNullOrEmpty($UserName)) { Write-Warning "UserName must be provided when DeviceData is not provided." break } } try { $time1 = Get-Date $xlFile = "$OutputFolder\$Title`_IntuneDevices_$(Get-Date -f 'yyyy-MM-dd').xlsx" Write-Verbose "output file = $xlFile" if ((Test-Path $xlFile) -and (!$Overwrite)) { Write-Warning "Output file exists [$xlFile]. Use -Overwrite to replace." break } if (!$DeviceData) { Write-Host "Requesting managed devices data from Intune" -ForegroundColor Cyan $DeviceData = Get-DsIntuneDevices -UserName $UserName -Detailed } else { Write-Warning "Device dataset should be derived with [-Detailed] option, to get the full set of properties." } if ($DeviceOS -ne 'All') { Write-Host "Filtering Intune devices by OSName: $DeviceOS" $DeviceData = $DeviceData | Where-Object {$_.OSName -eq $DeviceOS} Write-Host "Returned $($DeviceData.Count) devices running $DeviceOS" } Write-Host "Querying: installed applications for each device" $applist = Get-DsIntuneInstalledApps -DataSet $DeviceData if ($Distinct) { Write-Host "Filtering: unique product names per device" $applist2 = $applist | Select-Object DeviceName,ProductName | Sort-Object ProductName,DeviceName -Unique } Write-Host "Querying: AzureAD devices (you may be prompted for credentials)" -ForegroundColor Green $aaddevices = Get-DsIntuneAzureADDevices Write-Host "Found $($aaddevices.Count) AzureAD device accounts" if ($DeviceOS -ne 'All') { Write-Host "Filtering AzureAD devices by OSName: $DeviceOS" $aaddevices = $aaddevices | Where-Object {$_.OSName -match $DeviceOS} Write-Host "Returned $($aaddevices.Count) AzureAD devices running $DeviceOS" } Write-Host "Querying: Stale devices (more than $DaysOld days)" $stale = Get-DsIntuneStaleDevices -DataSet $DeviceData -Days $DaysOld Write-Host "Found $($stale.Count) devices not synchronized in the last $DaysOld days" Write-Host "Crunching statistics and stuff..." $stats = @() $stats += $aawin | Group-Object -Property IsCompliant | Select-Object Name,Count | % {[pscustomobject]@{Name = 'Compliant'; Property = $_.Name; Value = $_.Count}} $stats += $aawin | Group-Object -Property DirSyncEnabled | Select-Object Name,Count | % {[pscustomobject]@{Name = 'DirSyncEnabled'; Property = $_.Name; Value = $_.Count}} $stats += $aawin | Group-Object -Property TrustType | Select-Object Name,Count | % {[pscustomobject]@{Name = 'TrustType'; Property = $_.Name; Value = $_.Count}} $stats += $aawin | Group-Object -Property OSVersion | Select-Object Name,Count | ?{$_.Name -ne '' -and $_.Count -gt 5} | Sort-Object Count -Descending | % {[pscustomobject]@{Name = 'OSVersion'; Property = $_.Name; Value = $_.Count}} $stats += $aadevs | Group-Object -Property LastLogonDays | ?{$_.Name -gt 180 -and $_.Count -gt 10} | %{[pscustomobject]@{Name = 'DaysSinceLogon'; Count = $_.Count; Property = [int]$_.Name}} | Sort-Object Property -Descending $stats += $devices | Group-Object -Property Manufacturer,Model | Select-Object Name,Count | Sort-Object Count -Descending | %{[pscustomobject]@{Name = 'Models'; Property = $_.Name; Value = $_.Count}} $stats += $devices | Group-Object -Property Ownership | Select-Object Name,Count | Sort-Object Count -Descending | %{[pscustomobject]@{Name = 'Ownership'; Property = $_.Name; Value = $_.Count}} $stats += $devices | Group-Object -Property Category | Select-Object Name,Count | Sort-Object Count -Descending | %{[pscustomobject]@{Name = 'Category'; Property = $_.Name; Value = $_.Count}} $stats += $devices | Group-Object -Property UserName | Select-Object Name,Count | Where-Object {$_.Count -gt 1 -and $_.Name -ne ''} | Sort-Object Count -Descending | Select-Object -First 25 | %{[pscustomobject]@{Name = 'UserName'; Property = $_.Name; Value = $_.Count}} Write-Host "Exporting data to workbook..." $stats | Export-Excel -Path $XlFile -WorksheetName "Summary" -ClearSheet -AutoSize -FreezeTopRow -AutoFilter $aaddevices | Export-Excel -Path $xlFile -WorksheetName "AADDevices" -ClearSheet -AutoSize -FreezeTopRowFirstColumn -AutoFilter $DeviceData | Where-Object {$_.DeviceName -ne 'User deleted for this device'} | Select-Object * -ExcludeProperty Apps | Sort-Object DeviceName -Unique | Export-Excel -Path $xlFile -WorksheetName "IntuneDevices" -ClearSheet -AutoSize -FreezeTopRow -AutoFilter $stale | Select-Object * -ExcludeProperty Apps | Export-Excel -Path $XlFile -WorksheetName "StaleDevices" -ClearSheet -AutoSize -FreezeTopRow -AutoFilter $DeviceData | Where-Object {$_.DeviceName -eq 'User deleted for this device'} | Select-Object * -ExcludeProperty Apps | Sort-Object DeviceName,Manufacturer,Model | Export-Excel -Path $xlFile -WorksheetName "UserDeletedDevices" -ClearSheet -AutoSize -FreezeTopRow -AutoFilter $DeviceData | Where-Object {$_.FreeSpaceGB -lt 20 -and $_.OSName -eq 'Windows'} | Select-Object * -ExcludeProperty Apps | Sort-Object DeviceName,Manufacturer,Model | Export-Excel -Path $xlFile -WorksheetName "LowDisk" -ClearSheet -AutoSize -FreezeTopRow -AutoFilter $applist | Sort-Object ProductName | Export-Excel -Path $xlFile -WorksheetName "IntuneApps" -ClearSheet -AutoSize -FreezeTopRow -AutoFilter if ($null -ne $applist2) { $applist2 | Sort-Object ProductName,ProductVersion | Export-Excel -Path $xlFile -WorksheetName "DistinctApps" -ClearSheet -AutoSize -FreezeTopRow -AutoFilter } Write-Host "Results saved to: $xlFile" -ForegroundColor Green $time2 = Get-Date $rt = New-TimeSpan -Start $time1 -End $time2 Write-Host "Total runtime: $($rt.Hours)`:$($rt.Minutes)`:$($rt.Seconds) (hh`:mm`:ss)" -ForegroundColor Cyan if ($Show) { Start-Process -FilePath "$xlFile" } } catch { Write-Error $_.Exception.Message } } function Invoke-DsExcelQuery { <# .SYNOPSIS Query Excel Workbook/WorkSheet using SQL statement .DESCRIPTION Same as above .PARAMETER FilePath Path and filename to .xlsx workbook file .PARAMETER Query SQL query statement .EXAMPLE $xlFile = "c:\myfiles\IntuneDeviceData.xlsx" $query = "select DeviceName,ProductName from [IntuneApps$] where ProductName='Crapware 2019'" $rows = Invoke-DsExcelQuery -FilePath $xlFile -Query $query .NOTES NAME: Invoke-DsExcelQuery .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Invoke-DsExcelQuery.md #> [CmdletBinding()] param ( [parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $FilePath, [parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Query ) if (-not(Test-Path $FilePath)) { Write-Warning "file not found: $FilePath" break } try { $conn = New-Object System.Data.OleDb.OleDbConnection $cmd = New-Object System.Data.OleDb.OleDbCommand $connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=$FilePath;Extended Properties='Excel 12.0 Xml;HDR=YES;'" $conn.ConnectionString = $connstr $conn.Open() #$conn.GetSchema("tables") $cmd.CommandText = $query $cmd.CommandType = "Text" $cmd.Connection = $conn $dataReader = $cmd.ExecuteReader() $result = @() while ($dataReader.Read()) { $columns = $($dataReader.GetSchemaTable()).ColumnName $row = New-Object PSObject foreach ($column in $columns) { $row | Add-Member -MemberType NoteProperty -Name $column -Value $dataReader.item($column) } $result += $row } } catch { Write-Error $_.Exception.Message } finally { $conn.Close() $result } } function Invoke-DsIntuneAppQuery { <# .SYNOPSIS Query DataSet for unique App installation counts .DESCRIPTION Filters instances of application installations by Name/Title only to determine unique installations by device. Some devices will report multiple instances of the same application, with different ProductVersion numbers. This function excludes duplicates to show one-per-device only. .PARAMETER AppDataSet Device data returned from Get-DsIntuneDeviceData(). If not provided, Get-DsIntuneDeviceData() is invoked automatically. Passing Device data to -DeviceData can save significant processing time. .PARAMETER ProductName Application Product name .EXAMPLE $devices = Get-DsIntuneDeviceData -UserName "john.doe@contoso.com" $applist = Get-DsIntuneDeviceApps -DataSet $devices $rows = Invoke-DsIntuneAppQuery -AppDataSet $applist -ProductName "Acme Crapware 19.20 64-bit" .NOTES NAME: Invoke-DsIntuneAppQuery .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Invoke-DsIntuneAppQuery.md #> [CmdletBinding()] param ( [parameter(Mandatory)][ValidateNotNullOrEmpty()] $AppDataSet, [parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $ProductName ) try { $result = ($AppDataSet | Select-Object ProductName,DeviceName | Where-Object {$_.ProductName -eq $ProductName} | Sort-Object ProductName,DeviceName -Unique) } catch { Write-Error $_.Exception.Message } finally { $result } } function Test-DsIntuneUpdate { <# .SYNOPSIS Compare installed module version with latest in PS Gallery .DESCRIPTION Compare installed module version with latest in PS Gallery .EXAMPLE Test-DsIntuneUpdate .NOTES NAME: Test-DsIntuneUpdate .LINK https://github.com/Skatterbrainz/ds-intune/blob/master/docs/Test-DsIntuneUpdate.md #> [CmdletBinding()] param() try { $chkver = (Find-Module "ds-intune").Version $insver = ((Get-Module "ds-intune" | Sort-Object version -Descending).Version)[0] -join '.' if ($insver -lt $chkver) { Write-Warning "ds-intune $insver is installed. Latest version is $chkver. Use Update-Module ds-intune to update." } else { Write-Host "ds-intune $insver is installed. Latest version is $chkver." -ForegroundColor Green } } catch { Write-Host "(ds-intune) unable to check for module updates." Write-Error $_.Exception.Message } } Write-Host "This module is being deprecated. Please use module psIntune instead." -ForegroundColor Red |