<# .SYNOPSIS Exports device information from Microsoft Intune and sends a report via email. .DESCRIPTION This PowerShell script collects device data from Intune, filters it by device type (Windows, phones, and tablets) and exports the information to separate CSV files. The script then sends an email report with the exported files attached, providing a summary of the device information. .NOTES This script is intended for use in a test or production environment. Make sure to test the script in a non-production environment before running it in production. Author: D.de Kooker - info@dcomputers.nl Version: 0.1 DISCLAIMER: Use scripts at your own risk, if there is anything I can help you with I will try but I do not take responsibility for the way that anyone else uses my scripts. Sharing is caring. Share your knowledge with the world so that everybody can learn from it. .LINK The latest version can Always be found on my GIT page on the link below: https://git.dcomputers.nl/Dcomputers/PowershellScripts #> #region Global script settings and variables #General $Version = "v0.1" $logfilelocation = "$($MyInvocation.MyCommand.Path | Split-Path -Parent)\Logs" $logfilename = "$(Get-Date -Format yyyyMMddHHmmss)-Intune-Deviceinfo-export.log" $exportfilelocation = "$($MyInvocation.MyCommand.Path | Split-Path -Parent)\Exports" $summaryfilename = "$(Get-Date -Format yyyyMMddHHmmss)-Intune-Deviceinfo-Summary.txt" #Azure Enterprise app configuration $STR_TenantID = "" $STR_AppID = "" $STR_ClientSecret = "" #Email report settings $STR_SMTPServer = "" $STR_SMTPServerPort = "" $STR_SMTPUsername = "" $STR_SMTPPassword = "" $STR_EmailSubject= "Intune Device Export - $(Get-Date -Format "dd-MM-yyyy")" $STR_SMTPFromaddress = "Servicedesk ICT " $STR_Receivers = "servicedesk@contoso.com,systemengineer1@contoso.com" #List of commaseperated emailaddresses #endregion #region functions function SendMailv2 ($To,$Subject,$Body,$Attachments = @()){ $SMTPClient = New-Object Net.Mail.SmtpClient($STR_SMTPServer, $STR_SMTPServerPort) # $SMTPClient.EnableSsl = $true $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($STR_SMTPUsername, $STR_SMTPPassword); $SMTPMessage = New-Object System.Net.Mail.MailMessage($STR_SMTPFromaddress,$To,$Subject,$Body) $SMTPMessage.IsBodyHTML = $true # Add attachments if provided if ($Attachments.Count -gt 0) { foreach ($attachment in $Attachments) { $SMTPMessage.Attachments.Add((New-Object System.Net.Mail.Attachment($attachment))) } } $SMTPClient.Send($SMTPMessage) } function Initiate-Log { # Get current user and session information $username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $computerName = $env:COMPUTERNAME $sessionID = $pid $date = Get-Date -Format "yyyy-MM-dd HH:mm:ss" # Write log header $logHeader = "[$date] Log initiated by $username on $computerName (Session ID: $sessionID)" Add-Content -Path $logfilelocation\$logfilename -Value "**********************" Add-Content -Path $logfilelocation\$logfilename -Value "LogFile initiation" Add-Content -Path $logfilelocation\$logfilename -Value "Start time: $date" Add-Content -Path $logfilelocation\$logfilename -Value "Username: $username" Add-Content -Path $logfilelocation\$logfilename -Value "Machine: $computerName" Add-Content -Path $logfilelocation\$logfilename -Value "Process ID: $sessionID" Add-Content -Path $logfilelocation\$logfilename -Value "Script Version: $Version" Add-Content -Path $logfilelocation\$logfilename -Value "Script Source: https://git.dcomputers.nl/Dcomputers/PowershellScripts" Add-Content -Path $logfilelocation\$logfilename -Value "**********************" } function Write-Log { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [string]$Message, [Parameter(Mandatory=$false)] [ValidateSet("INFO", "WARNING", "ERROR")] [string]$Level = "INFO" ) $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $logmessage = "[$timestamp] [$Level] $Message" Add-Content -Path $logfilelocation\$logfilename -Value $logmessage } function Write-Summary { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [string]$Message ) Add-Content -Path $logfilelocation\$summaryfilename -Value $Message } #endregion #region prerequisites check #Create log directory if not present and initiate logfile if (!(test-path $logfilelocation)) {mkdir $logfilelocation} if (!(test-path $exportfilelocation)) {mkdir $exportfilelocation} Initiate-Log #Check if the required Powershell Modules are available $modules = @("Microsoft.Graph") foreach ($module in $modules) { if (!(Get-Module -Name $module -ListAvailable)) { Write-Host "The $module module is not installed. Please install it and try again." Write-Log -Message "The $module module is not installed. Please install it and try again." -Level ERROR exit 1 } } #Setup MSGraph connection $ClientSecretPass = ConvertTo-SecureString -String $STR_ClientSecret -AsPlainText -Force $ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $STR_AppID, $ClientSecretPass Connect-MgGraph -TenantId $STR_TenantID -ClientSecretCredential $ClientSecretCredential Write-Log -Message "Connected to MsGraph API" -Level INFO #endregion #region Collect device information from Intune #Get all devices from Intune $devices = Get-MgDeviceManagementManagedDevice -All $devicesbasic = Get-MgDevice -all if ($null -ne $devices.Count){ Write-Log -Message "Found $($devices.Count) devices in Intune" -Level INFO } else { Write-Log -Message "Unable to collect Device information from intune" -Level ERROR exit 1 } #Filter and export all device information for the different device types #Windows Fysical devices $windowsdevices = $devices | Where-Object {$_.OperatingSystem -eq 'Windows' -and $_.Model -ne 'Virtual Machine' -and $_.ManagedDeviceOwnerType -eq 'company'} $windevinfo = @() #Loop devices and gather information foreach ($windowsdevice in $windowsdevices){ $windowsdevicedetails = [PSCustomObject]@{ DeviceName = $windowsdevice.DeviceName EnrolledDateTime = ($windowsdevice.EnrolledDateTime).ToString("dd-MM-yyyy HH:mm:ss") EnrollmentProfile = $($devicesbasic | Where-Object {$_.DisplayName -eq "$($windowsdevice.DeviceName)"} | Select-Object -First 1 -ExpandProperty EnrollmentProfileName) Manufacturer = $windowsdevice.Manufacturer Model = $windowsdevice.Model ManagedDeviceOwnerType = $windowsdevice.ManagedDeviceOwnerType OperatingSystem = $windowsdevice.OperatingSystem SerialNumber = $windowsdevice.SerialNumber PrimairyUser = $windowsdevice.UserPrincipalName } $windevinfo += $windowsdevicedetails } #Export device information to csv $windevexport = "$exportfilelocation\$(Get-Date -Format yyyyMMddHHmmss)-WindowsDevices.csv" $windevinfo | Export-Csv -Path $windevexport -NoTypeInformation #Phone and tablets $phonesandtablets = $devices | Where-Object {($_.Manufacturer -eq 'Apple' -or $_.OperatingSystem -eq 'Android') -and $_.ManagedDeviceOwnerType -eq 'company'} $phonesandtabletinfo = @() #Loop devices and gather information foreach ($device in $phonesandtablets){ $phonesandtabletsdetails = [PSCustomObject]@{ DeviceName = $device.DeviceName EnrolledDateTime = ($device.EnrolledDateTime).ToString("dd-MM-yyyy HH:mm:ss") EnrollmentProfile = $($devicesbasic | Where-Object {$_.DisplayName -eq "$($device.DeviceName)"} | Select-Object -First 1 -ExpandProperty EnrollmentProfileName) Imei = $device.Imei PhoneNumber = $device.PhoneNumber Manufacturer = $device.Manufacturer Model = $device.Model ManagedDeviceOwnerType = $device.ManagedDeviceOwnerType OperatingSystem = $device.OperatingSystem SerialNumber = $device.SerialNumber PrimairyUser = $device.UserPrincipalName } $phonesandtabletinfo += $phonesandtabletsdetails } #Export device information to csv $phonesandtabletsexport = "$exportfilelocation\$(Get-Date -Format yyyyMMddHHmmss)-PhonesandTablets.csv" $phonesandtabletinfo | Export-Csv -Path $phonesandtabletsexport -NoTypeInformation #endregion #region send reports and generate summary report # Send the report via email $emailbody = @"

Intune Device exports - $(Get-Date -Format "dd-MM-yyyy - HH:mm")

Script version: $Version
Please see attached the exports split for company owned devices.
This is an automated report.

"@ $emailattachments = $($windevexport,$phonesandtabletsexport) SendMailv2 -To $STR_Receivers -Subject $STR_EmailSubject -Body $emailbody -Attachments $emailattachments #endregion