Modul_Cleoni_Download.psm1

function func_DownloadPackage($Path, $tempFolder, $Filename, $Joblist)
{
    function Write-Status($Text) {
        Write-Output $Text.trim()
        $new = [Environment]::NewLine
        Write-Output $new
    }
    function Module-Install() {
     Install-PackageProvider -Name NuGet -Scope CurrentUser -Confirm:$false -Force | Out-Null

     $Modulpath = -join([System.Environment]::GetFolderPath("MyDocuments"), '\WindowsPowerShell\Modules')
     If (!(Test-Path -Path $Modulpath)) {New-Item -Path $Modulpath -ItemType Directory | out-null}
      If (!(Get-InstalledModule Microsoft.Graph -ErrorAction SilentlyContinue)) {
         Write-Status -Text 'Microsoft.Graph Module installation...'
         Save-Module -Name Microsoft.Graph -Path $Modulpath
     }
     Import-Module Microsoft.Graph.Users | Out-Null
     Import-Module Microsoft.Graph.Groups | Out-Null
     
     If (!(Get-InstalledModule Microsoft.Graph.Intune -ErrorAction SilentlyContinue)) {
         Write-Status -Text 'Microsoft.Graph.Intune Module installation...'
         Save-Module -Name Microsoft.Graph.Intune -Path $Modulpath
     }
     Import-Module Microsoft.Graph.Intune -ErrorAction Stop | Out-Null
     
     If (!(Get-InstalledModule ImportExcel -ErrorAction SilentlyContinue)) {
         Write-Status -Text 'ImportExcel Module installation...'
         Save-Module -Name ImportExcel -Path $Modulpath
     }        
     Import-Module ImportExcel | Out-Null
     ###################################################
    }
    function Cleoni-Download($Path, $Joblist) {
        function Download-ClientApp($Path) {
            [string]$ApiVersion = "Beta"    
     
            # Create folder if not exists
            if (-not (Test-Path "$Path\Client Apps")) {
                $null = New-Item -Path "$Path\Client Apps" -ItemType Directory
            }
     
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
     
            # Get all Client Apps
            $clientApps = Get-DeviceAppManagement_MobileApps | Get-MSGraphAllPages
     
            foreach ($clientApp in $clientApps) {
                $clientAppType = $clientApp.'@odata.type'.split('.')[-1]
                $fileName = ($clientApp.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                $clientAppDetails = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceAppManagement/mobileApps/$($clientApp.id)"
                $clientAppDetails | ConvertTo-Json | Out-File -LiteralPath "$path\Client Apps\$fileName.json"
            }
        }
        function Download-ClientAppAssignment($Path) {
            [string]$ApiVersion = "Beta"
            # Create folder if not exists
            if (-not (Test-Path "$Path\Client Apps\Assignments")) {
                $null = New-Item -Path "$Path\Client Apps\Assignments" -ItemType Directory
            }
       
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
   
            # Get all assignments from all policies
            $clientApps = Get-DeviceAppManagement_MobileApps | Get-MSGraphAllPages
   
            foreach ($clientApp in $clientApps) {
                $assignments = Get-DeviceAppManagement_MobileApps_Assignments -MobileAppId $clientApp.id
                $assignments | Add-Member -MemberType NoteProperty -Name 'DisplayName' -Value $clientApp.displayName -Force
                if ($assignments) {
                    $fileName = ($clientApp.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                    $assignments | ConvertTo-Json -Depth 3 | Out-File -LiteralPath "$path\Client Apps\Assignments\$fileName.json"
                }
           
            }
        }
        function Download-DeviceCompliancePolicy($Path) {
            [string]$ApiVersion = "Beta"
            # Create folder if not exists
            if (-not (Test-Path "$Path\Device Compliance Policies")) {
                $null = New-Item -Path "$Path\Device Compliance Policies" -ItemType Directory
            }
       
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
       
            # Get all Device Compliance Policies
            $deviceCompliancePolicies = Get-DeviceManagement_DeviceCompliancePolicies | Get-MSGraphAllPages
       
            foreach ($deviceCompliancePolicy in $deviceCompliancePolicies) {
                $fileName = ($deviceCompliancePolicy.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                $deviceCompliancePolicy | ConvertTo-Json | Out-File -LiteralPath "$path\Device Compliance Policies\$fileName.json"
            }
        }
        function Download-DeviceCompliancePolicyAssignment($Path) {
            [string]$ApiVersion = "Beta"
            # Create folder if not exists
            if (-not (Test-Path "$Path\Device Compliance Policies\Assignments")) {
                $null = New-Item -Path "$Path\Device Compliance Policies\Assignments" -ItemType Directory
            }
       
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
            # Get all assignments from all policies
            $deviceCompliancePolicies = Get-DeviceManagement_DeviceCompliancePolicies | Get-MSGraphAllPages
   
            foreach ($deviceCompliancePolicy in $deviceCompliancePolicies) {
                $assignments = Get-DeviceManagement_DeviceCompliancePolicies_Assignments -DeviceCompliancePolicyId $deviceCompliancePolicy.id
                $assignments | Add-Member -MemberType NoteProperty -Name 'DisplayName' -Value $deviceCompliancePolicy.displayName -Force
                if ($assignments) {
                    $fileName = ($deviceCompliancePolicy.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                    $assignments | ConvertTo-Json | Out-File -LiteralPath "$path\Device Compliance Policies\Assignments\$fileName.json"
                }
            }
        }
        function Download-DeviceConfiguration($Path) {
            [string]$ApiVersion = "Beta"
            # Create folder if not exists
            if (-not (Test-Path "$Path\Device Configurations")) {
                $null = New-Item -Path "$Path\Device Configurations" -ItemType Directory
            }
       
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
                
            # Get all device configurations
            $deviceConfigurations = Get-DeviceManagement_DeviceConfigurations | Get-MSGraphAllPages
                
                
            foreach ($deviceConfiguration in $deviceConfigurations) {
                $fileName = ($deviceConfiguration.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                
                # If it's a custom configuration, check if the device configuration contains encrypted OMA settings, then decrypt the OmaSettings to a Plain Text Value (required for import)
                if (($deviceConfiguration.'@odata.type' -eq '#microsoft.graph.windows10CustomConfiguration') -and ($deviceConfiguration.omaSettings | Where-Object { $_.isEncrypted -contains $true } )) {
                    # Create an empty array for the unencrypted OMA settings.
                    $newOmaSettings = @()
                    foreach ($omaSetting in $deviceConfiguration.omaSettings) {
                        # Check if this particular setting is encrypted, and get the plaintext only if necessary
                        if ($omaSetting.isEncrypted) {
                            $omaSettingValue = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/deviceConfigurations/$($deviceConfiguration.id)/getOmaSettingPlainTextValue(secretReferenceValueId='$($omaSetting.secretReferenceValueId)')" | Get-MSGraphAllPages
                        }
                        # Define a new 'unencrypted' OMA Setting
                        $newOmaSetting = @{}
                        $newOmaSetting.'@odata.type' = $omaSetting.'@odata.type'
                        $newOmaSetting.displayName = $omaSetting.displayName
                        $newOmaSetting.description = $omaSetting.description
                        $newOmaSetting.omaUri = $omaSetting.omaUri
                        $newOmaSetting.value = $omaSettingValue
                        $newOmaSetting.isEncrypted = $false
                        $newOmaSetting.secretReferenceValueId = $null
                
                        # Add the unencrypted OMA Setting to the Array
                        $newOmaSettings += $newOmaSetting
                    }
                
                    # Remove all encrypted OMA Settings from the Device Configuration
                    $deviceConfiguration.omaSettings = @()
                
                    # Add the unencrypted OMA Settings from the Device Configuration
                    $deviceConfiguration.omaSettings += $newOmaSettings
                }
                
                # Export the Device Configuration Profile
                $deviceConfiguration | ConvertTo-Json -Depth 100 | Out-File -LiteralPath "$path\Device Configurations\$fileName.json"
            }
        }
        function Download-DeviceConfigurationAssignment($Path) {
            [string]$ApiVersion = "Beta"
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
   
            # Create folder if not exists
            if (-not (Test-Path "$Path\Device Configurations\Assignments")) {
                $null = New-Item -Path "$Path\Device Configurations\Assignments" -ItemType Directory
            }
       
            # Get all assignments from all policies
            $deviceConfigurations = Get-DeviceManagement_DeviceConfigurations | Get-MSGraphAllPages
   
            foreach ($deviceConfiguration in $deviceConfigurations) {
                $assignments = Get-DeviceManagement_DeviceConfigurations_Assignments -DeviceConfigurationId $deviceConfiguration.id
                $assignments | Add-Member -MemberType NoteProperty -Name 'DisplayName' -Value $deviceConfiguration.displayName -Force
                if ($assignments) {
                    $fileName = ($deviceConfiguration.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                    $assignments | ConvertTo-Json | Out-File -LiteralPath "$path\Device Configurations\Assignments\$fileName.json"
                }
            }
   
        }
        function Download-CatalogSettings($Path) {      
                
            [string]$ApiVersion = "Beta"
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
                
            # Create folder if not exists
            if (-not (Test-Path "$Path\Settings Catalog")) {
                $null = New-Item -Path "$Path\Settings Catalog" -ItemType Directory
            }
                
            # Get all Setting Catalogs Policies
            $configurationPolicies = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/configurationPolicies" | Get-MSGraphAllPages
                
            foreach ($configurationPolicy in $configurationPolicies) {
                $configurationPolicy | Add-Member -MemberType NoteProperty -Name 'settings' -Value @() -Force
                $settings = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/configurationPolicies/$($configurationPolicy.id)/settings" | Get-MSGraphAllPages
                
                if ($settings -isnot [System.Array]) {
                    $configurationPolicy.Settings = @($settings)
                }
                else {
                    $configurationPolicy.Settings = $settings
                }
                     
                $fileName = ($configurationPolicy.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                $configurationPolicy | ConvertTo-Json -Depth 100 | Out-File -LiteralPath "$path\Settings Catalog\$fileName.json"
                     
                [PSCustomObject]@{
                    "Action" = "Backup"
                    "Type"   = "Settings Catalog"
                    "Name"   = $configurationPolicy.name
                    "Path"   = "Settings Catalog\$fileName.json"
                }
            }

        }
        function Download-CatalogSettingsAssignment($Path) {
                
            [string]$ApiVersion = "Beta"
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
                
            # Create folder if not exists
            if (-not (Test-Path "$Path\Settings Catalog\Assignments")) {
                $null = New-Item -Path "$Path\Settings Catalog\Assignments" -ItemType Directory
            }
                
            # Get all Setting Catalogs Policies
            $configurationPolicies = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/configurationPolicies" | Get-MSGraphAllPages
                
            foreach ($configurationPolicy in $configurationPolicies) {
                $configurationPolicy | Add-Member -MemberType NoteProperty -Name 'target' -Value @() -Force
                $configurationPolicy | Add-Member -MemberType NoteProperty -Name 'DisplayName' -Value $configurationPolicy.name -Force
                $settings = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/configurationPolicies/$($configurationPolicy.id)/assignments" | Get-MSGraphAllPages
                
                if ($settings -isnot [System.Array]) {
                    $configurationPolicy.target += @($settings.target)
                }
                else {
                    $configurationPolicy.target += $settings.target
                }             

                $fileName = ($configurationPolicy.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                $configurationPolicy | ConvertTo-Json -Depth 100 | Out-File -LiteralPath "$path\Settings Catalog\Assignments\$fileName.json"

            }

        }
        function Download-EndpointSecurity($Path) {
            [string]$ApiVersion = "Beta"
            # Create folder if not exists
            if (-not (Test-Path "$Path\EndpointSecurity")) {
                $null = New-Item -Path "$Path\EndpointSecurity" -ItemType Directory
            }
       
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
   
            $intents = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/intents" | Get-MSGraphAllPages
   
            foreach ($intent in $intents) {
                # Get the corresponding Device Management Template
                $template = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/templates/$($intent.templateId)"
                $templateDisplayName = ($template.displayName).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
   
                if (-not (Test-Path "$Path\EndpointSecurity\$templateDisplayName")) {
                    $null = New-Item -Path "$Path\EndpointSecurity\$templateDisplayName" -ItemType Directory
                }
           
                # Get all setting categories in the Device Management Template
                $templateCategories = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/templates/$($intent.templateId)/categories" | Get-MSGraphAllPages
   
                $intentSettingsDelta = @()
                foreach ($templateCategory in $templateCategories) {
                    # Get all configured values for the template categories
                    $intentSettingsDelta += (Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/intents/$($intent.id)/categories/$($templateCategory.id)/settings").value
                }
   
                $intentBackupValue = @{
                    "displayName"     = $intent.displayName
                    "description"     = $intent.description
                    "settingsDelta"   = $intentSettingsDelta
                    "roleScopeTagIds" = $intent.roleScopeTagIds
                }
           
                $deviceManagementIntentFileName = $($intent.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                $intentBackupValue | ConvertTo-Json | Out-File -LiteralPath "$path\EndpointSecurity\$templateDisplayName\$deviceManagementIntentFileName.json"
            }
        }
        function Download-DeviceManagementScript($path) {
            [string]$ApiVersion = "Beta"
            # Create folder if not exists
            if (-not (Test-Path "$Path\Device Management Scripts\Script Content")) {
                $null = New-Item -Path "$Path\Device Management Scripts\Script Content" -ItemType Directory
            }
       
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
       
            # Get all device management scripts
            $deviceManagementScripts = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/deviceManagementScripts" | Get-MSGraphAllPages
   
            foreach ($deviceManagementScript in $deviceManagementScripts) {
                # ScriptContent returns null, so we have to query Microsoft Graph for each script
                $deviceManagementScriptObject = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/deviceManagementScripts/$($deviceManagementScript.Id)"
                $deviceManagementScriptFileName = ($deviceManagementScriptObject.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'

                $deviceManagementScriptObject | Add-Member -MemberType NoteProperty -Name 'DisplayName' -Value $deviceManagementScriptObject.displayName -Force
                $deviceManagementScriptObject | ConvertTo-Json | Out-File -LiteralPath "$path\Device Management Scripts\$deviceManagementScriptFileName.json"
            }
        }
        function Download-DeviceManagementScriptAssignment($Path) {
            [string]$ApiVersion = "Beta"
            # Create folder if not exists
            if (-not (Test-Path "$Path\Device Management Scripts\Assignments")) {
                $null = New-Item -Path "$Path\Device Management Scripts\Assignments" -ItemType Directory
            }
         
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
         
            # Get all assignments from all policies
            $deviceManagementScripts = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/deviceManagementScripts" | Get-MSGraphAllPages
   
            foreach ($deviceManagementScript in $deviceManagementScripts) {
                $assignments = Invoke-MSGraphRequest -HttpMethod GET -Url "deviceManagement/deviceManagementScripts/$($deviceManagementScript.id)/assignments" | Get-MSGraphAllPages
           
                if ($assignments) {
                    $assignments | Add-Member -MemberType NoteProperty -Name 'DisplayName' -Value $deviceManagementScript.displayName -Force
                    $fileName = ($deviceManagementScript.displayName).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                    $assignments | ConvertTo-Json | Out-File -LiteralPath "$path\Device Management Scripts\Assignments\$fileName.json"
                }
            }
        }
        function Download-DeviceEnrollmentStatusPage($Path) {
            [string]$ApiVersion = "Beta"    
       
            # Create folder if not exists
            if (-not (Test-Path "$Path\DeviceEnrollment")) {
                $null = New-Item -Path "$Path\DeviceEnrollment" -ItemType Directory
            }
   
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
       
            # Get all Status Pages
            $StatusPages = Get-DeviceManagement_DeviceEnrollmentConfigurations | Get-MSGraphAllPages
   
            foreach ($StatusPage in $StatusPages) {
                $StatusPage | Add-Member -MemberType NoteProperty -Name 'DisplayName' -Value $StatusPage.displayName -Force
                $fileName = ($StatusPage.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                $StatusPage | ConvertTo-Json | Out-File -LiteralPath "$Path\DeviceEnrollment\$fileName.json"

            }
        }
        function Download-DeploymentProfiles($Path) {
            [string]$ApiVersion = "Beta"
            # Set the Microsoft Graph API endpoint
            if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
                Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
                Connect-MSGraph -ForceNonInteractive -Quiet
            }
   
            # Create folder if not exists
            if (-not (Test-Path "$Path\DeploymentsProfiles")) {
                $null = New-Item -Path "$Path\DeploymentProfiles" -ItemType Directory
            }
       
            # Get all DeploymentProfiles
            $DeviceProfiles = Get-GraphWindowsAutopilotDeploymentProfile | Get-MSGraphAllPages
   
            foreach ($DeviceProfile in $DeviceProfiles) {
                $DeviceProfile | Add-Member -MemberType NoteProperty -Name 'DisplayName' -Value $DeviceProfile.displayName -Force
                $fileName = ($DeviceProfile.id).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
                $DeviceProfile | ConvertTo-Json | Out-File -LiteralPath "$Path\DeploymentProfiles\$fileName.json"
            }
        }
    
        #Download Client Apps
        If ($Joblist.chk_Apps -eq $true) {
            try {
                Write-Status -Text 'Apps downloading...'
                Download-ClientApp $Path | Out-Null
            }
            catch { Write-Status -Text 'App ERROR...' }
        }
               
        #Download Client Apps Assignments
        If ($Joblist.chk_AppAssignment -eq $true) {
            try {
                Write-Status -Text 'App Assignments downloading...'
                Download-ClientAppAssignment $Path | Out-Null
            }
            catch { Write-Status -Text 'App Assignments ERROR...' }
        }

        #Download Deployment Profiles
        If ($Joblist.chk_Deployment -eq $true) {
            try {
                Write-Status -Text 'Deployment Profiles downloading...'
                Download-DeploymentProfiles $Path | Out-Null
            }
            catch { Write-Status -Text 'Deployment Profiles ERROR...' }
        }

        #Download Device Compliance Policies
        If ($Joblist.chk_DeviceCompliancePolicies -eq $true) {
            try {
                Write-Status -Text 'Device Compliancepolicies downloading...'
                Download-DeviceCompliancePolicy $Path | Out-Null
            }
            catch { Write-Status -Text 'Device Compliancepolicies ERROR...' }
        }

        #Download Device Compliance Policy Assignment
        If ($Joblist.chk_DeviceCompliancePolicyAssignment -eq $true) {
            try {
                Write-Status -Text 'Device Compliancepolicy Assignments downloading...'
                Download-DeviceCompliancePolicyAssignment $Path | Out-Null
            }
            catch { Write-Status -Text 'Device Compliancepolicy Assignments ERROR...' }
        }

        #Download Device Configurations
        If ($Joblist.chk_DeviceConfigurations -eq $true) {
            try {
                Write-Status -Text 'Device Configuration downloading...'
                Download-DeviceConfiguration $Path | Out-Null
            }
            catch { Write-Status -Text 'Device Configurations ERROR...' }
        }

        #Download Settings Catalog
        If ($Joblist.chk_SettingsCatalog -eq $true) {
            try {
                Write-Status -Text 'Settings Catalog downloading...'
                Download-CatalogSettings $Path | Out-Null
                Download-CatalogSettingsAssignment $Path | Out-Null
            }
            catch { Write-Status -Text 'Settings Catalog ERROR...' }
        }

        #Download Settings Catalog Assignments
        If ($Joblist.chk_SettingsCatalogAssignment -eq $true) {
            try {
                Write-Status -Text 'Settings Catalog Assignments downloading...'
                Download-CatalogSettingsAssignment $Path | Out-Null
            }
            catch { Write-Status -Text 'Settings Catalog Assignments ERROR...' }
        }

        #Download Device Configuration Assignments
        If ($Joblist.chk_DeviceConfigurationAssignments -eq $true) {
            try {
                Write-Status -Text 'Device Configuration Assignments downloading...'
                Download-DeviceConfigurationAssignment $Path | Out-Null
            }
            catch { Write-Status -Text 'Device Configuration Assignments ERROR...' }
        }

        #Download Device Enrollment Status Page
        If ($Joblist.chk_DeviceEnrollmentStatusPage -eq $true) {
            try {
                Write-Status -Text 'Enrollment Status Pages downloading...'
                Download-DeviceEnrollmentStatusPage $Path | Out-Null
            }
            catch { Write-Status -Text 'Enrollment Status Pages ERROR...' }
        }

        #Download Device Management Scripts
        If ($Joblist.chk_DeviceManagementScripts -eq $true) {
            try {
                Write-Status -Text 'Device Management Scripts downloading...'
                Download-DeviceManagementScript $Path | Out-Null
            }
            catch { Write-Status -Text 'Device Management Script ERROR...' }
        }

        #Download Device Management Script Assignments
        If ($Joblist.chk_DeviceManagementScriptAssignments -eq $true) {
            try {
                Write-Status -Text 'Device Management Script Assignments downloading...'
                Download-DeviceManagementScriptAssignment $Path | Out-Null
            }
            catch { Write-Status -Text 'Device Management Script Assignments ERROR...' }
        }

        #Download Endpoint Security
        If ($Joblist.chk_EndpointSecurity -eq $true) {            
            try {
                Write-Status -Text 'EndpointSecurity downloading...'
                Download-EndpointSecurity $Path | Out-Null
            }
            catch { Write-Status -Text 'EndpointSecurity ERROR...' }
        }

        Write-Status -Text 'Download completed !'
        
    } 
    function Cleoni-Convert($Path, $Joblist) {
        function New-Hash([string]$text) {
            $md5 = [Security.Cryptography.MD5CryptoServiceProvider]::new()
            $utf8 = [Text.UTF8Encoding]::UTF8
            $bytes = $md5.ComputeHash($utf8.GetBytes($text))
            $hash = [string]::Concat($bytes.foreach{ $_.ToString("x2") }) 
            return $hash
        }
        function Convert-Assignments($Command, $Source, $Destination) {
            function Join-String {
                [CmdletBinding()]
                Param(
                    [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]]$StringArray, 
                    $Separator = ",",
                    [switch]$DoubleQuote = $false
                )
                BEGIN {
                    $joinArray = [System.Collections.ArrayList]@()
                }
                PROCESS {
                    foreach ($astring in $StringArray) {
                        $joinArray.Add($astring) | Out-Null
                    }
                }
                END {
                    $Object = [PSCustomObject]@{}
                    $count = 0;
                    foreach ($aString in $joinArray) {

                        $name = "ieo_$($count)"
                        $Object | Add-Member -MemberType NoteProperty -Name $name -Value $aString;
                        $count = $count + 1;
                    }
                    $ObjectCsv = $Object | ConvertTo-Csv -NoTypeInformation -Delimiter $separator
                    $result = $ObjectCsv[1]
                    if (-not $DoubleQuote) {
                        $result = $result.Replace('","', ",").TrimStart('"').TrimEnd('"')
                    }
                    return $result
                }
            }
            function func_ReadAssignments($value) {
    
                [array]$assignments = $null
                          
                $Line = '' | Select Mode, Assign
                Foreach ($valuetarget in $value.target) {
                    If ($valuetarget."@odata.type" -eq "#microsoft.graph.allDevicesAssignmentTarget") {
                        $assignments += 'All Devices'
                        $Line.Mode = 'Included'
                    }
                    elseIf ($valuetarget."@odata.type" -eq "#microsoft.graph.allLicensedUsersAssignmentTarget") {
                        $assignments += 'All Users'
                        $Line.Mode = 'Included'
                    }
                    elseif ($valuetarget."@odata.type" -eq "#microsoft.graph.groupAssignmentTarget") {
                        $assignments += Get-MgGroup | Where-Object {$_.ID -eq $valuetarget.groupId} | Select-Object -ExpandProperty DisplayName
                        $Line.Mode = 'Included'
                    }
                    elseif ($valuetarget."@odata.type" -eq "#microsoft.graph.exclusionGroupAssignmentTarget") {
                        $assignments += Get-MgGroup | Where-Object {$_.ID -eq $valuetarget.groupId} | Select-Object -ExpandProperty DisplayName
                        $Line.Mode = 'Excluded'
                    }                      
                }
                          
                $Line.Assign = $assignments
                return $Line
            }
                          
            $List = @()
            Foreach ($file in Get-ChildItem $Source -File) {
                $values = Get-Content -Path $file.Fullname -ErrorAction SilentlyContinue | ConvertFrom-Json
                $all_intents = $values.intent | Sort-Object -Unique
                $all_modes = $values.target."@odata.type" | Sort-Object -Unique

                if ($all_intents) {

                    Foreach ($intent in $all_intents) {  
                        Foreach ($mode in $all_modes) {
                   
                            $filter_value = $values | Where-Object { $_.target."@odata.type" -eq $mode -and $_.intent -eq $intent}
                            try { $result = func_ReadAssignments -value $filter_value }catch {}
                                                            
                            If ($result.assign) {
                                $Line = '' | Select Name, ObjectID, Intent, Mode, Assignment, Hash
                                $Line.Name = $values[0].Displayname
                                $Line.ObjectID = $values[0].$Command
                                $Line.Intent = $intent
                                $Line.Mode = $result.mode
                                $Line.Assignment = If ($result.assign -gt 1) { $result.assign | Join-String -Separator ',' }else { $result.assign }
                                $Line.Hash = New-Hash -text "$(-join($Line.Name, $Line.ObjectID, $Line.Intent, $Line.Mode))"
                               
                                $List += $Line
                            }
                        }               
                    }
                }
                else {
              
                    Foreach ($mode in $all_modes) {     
                        $filter_value = $values | Where-Object { $_.target."@odata.type" -eq $mode }
                        try{ $result = func_ReadAssignments -value $filter_value } catch{}
                
                        If ($result.assign) {
                            $Line = '' | Select Name, ObjectID, Mode, Assignment, Hash
                            $Line.Name = $values[0].Displayname
                            $Line.ObjectID = $values[0].$Command
                            $Line.Mode = $result.mode
                            $Line.Assignment = If ($result.assign -gt 1) { $result.assign | Join-String -Separator ',' }else { $result.assign }
                            $Line.Hash = New-Hash -text "$(-join($Line.Name, $Line.ObjectID, $Line.Mode))"
                            $List += $Line
                        }
                    }
                }
            }
            $List | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue          
        }
        function Convert-Apps($Source, $Destination) {
            $AppConfigs_Path = $Source
            $results = @()
            Foreach ($entry in Get-ChildItem -Path $AppConfigs_Path) {
                $App = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json  | Select-Object DisplayName, ID, publisher, createdDateTime, lastModifiedDateTime, fileName, size, installcommandLine, uninstallcommandline, applicableArchitectures, setupFilePath, detectionRules, minimumSupportedWindowsRelease
      
                If ($App.detectionRules) {
                    $Members = $App.detectionRules | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
                    [string]$DetectionList = @()
   
                    $maxMembers = $Members.Count
                    $NrMember = 1
                    Foreach ($Member in $Members) {
                        If ($NrMember -eq $maxMembers) { $LastMember = '' }else { $LastMember = ', ' }
                        If ($Member -eq 'scriptContent') {
                            $DetectionList += -join ($Member, ' = ', 'yes', $LastMember)
                        }
                        else { $DetectionList += -join ($Member, ' = ', [string]$($App.detectionRules.$Member), $LastMember) }
   
                        $NrMember += 1
                    } 
                    $properties = [ordered]@{
                        displayName                    = $App.'displayName'
                        ID                             = $App.'id'
                        publisher                      = $App.'publisher'
                        createdDateTime                = $App.'createdDateTime'
                        lastModifiedDateTime           = $App.'lastModifiedDateTime'
                        fileName                       = $App.'fileName'
                        size                           = $App.'size'
                        installCommandLine             = $App.'installCommandLine'
                        uninstallCommandLine           = $App.'uninstallCommandLine'
                        applicableArchitectures        = $App.'applicableArchitectures'
                        setupFilePath                  = $App.'setupFilePath'
                        detectionRules                 = $($DetectionList -join ',')
                        minimumSupportedWindowsRelease = $App.'minimumSupportedWindowsRelease'
                        Hash                           = New-Hash -text "$(-join($App.ID, $App.DisplayName))"
                    }
      
                    $results += New-Object psobject -Property $properties
                }
     
            }
            $results | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
        }
        function Convert-DeviceCompliancePolicy($Source, $Destination) {
            $AppConfigs_Path = $Source
            $AppList = @()
            Foreach ($entry in Get-ChildItem -Path $AppConfigs_Path) {
                $Line = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json | Select-Object DisplayName,
                ID,
                createdDateTime, 
                lastModifiedDateTime, 
                passwordRequired, 
                passwordBlockSimple, 
                passwordRequiredToUnlockFromIdle,
                passwordMinutesOfInactivityBeforeLock,
                passwordExpirationDays,
                passwordMinimumLength,
                passwordMinimumCharacterSetCount,
                passwordRequiredType,
                passwordPreviousPasswordBlockCount,
                requireHealthyDeviceReport,
                osMinimumVersion,
                osMaximumVersion,
                mobileOsMinimumVersion,
                mobileOsMaximumVersion,
                earlyLaunchAntiMalwareDriverEnabled,
                bitLockerEnabled,
                secureBootEnabled,
                codeIntegrityEnabled,
                storageRequireEncryption,
                activeFirewallRequired,
                defenderEnabled,
                defenderVersion,
                signatureOutOfDate,
                rtpEnabled,
                antivirusRequired,
                antiSpywareRequired,
                deviceThreatProtectionEnabled,
                deviceThreatProtectionRequiredSecurityLevel,
                configurationManagerComplianceRequired,
                tpmRequired,
                deviceCompliancePolicyScript,
                deviceCompliancePolicyId

                $NewHash = New-Hash -text "$(-join($Line.ID, $Line.DisplayName))"
                $Line | Add-Member -MemberType NoteProperty -Name 'Hash' -Value $NewHash -Force
                $AppList += $Line
            }
            
            $AppList | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
        }
        function Convert-DeviceConfigurations($Source, $Destination) {
            $AppConfigs_Path = $Source
            $AppList = @()
            Foreach ($entry in Get-ChildItem -Path $AppConfigs_Path) {
                $FirstLine = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json | Select-Object '@odata.type', Displayname, ID, CreatedDateTime, LastModifiedDateTime
                $LastLine = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json | Select-Object -ExcludeProperty '@odata.type', Displayname, ID, CreatedDateTime, LastModifiedDateTime
              
                $LastLineMembers = @()
              
                If ($LastLine) {
                    $LastLineMembers = Get-Member -InputObject $LastLine -MemberType NoteProperty | Select-Object -ExpandProperty Name

                    Foreach ($LastLineMember in $LastLineMembers) {
               
                        If ($LastLine."$LastLineMember" -ne 'System.Object[]' -and $LastLineMember -ne '@odata.type') {
                            $Line = '' | Select Type, Displayname, ID, CreatedDateTime, LastModifiedDateTime, Property, Value, Hash 
                            $Line.Type = $FirstLine.'@odata.type'
                            $Line.Displayname = $FirstLine.displayName
                            $Line.ID = $FirstLine.id
                            $Line.CreatedDateTime = $FirstLine.createdDateTime
                            $Line.LastModifiedDateTime = $FirstLine.lastModifiedDateTime
                            $Line.Property = $LastLineMember
                            $Line.Value = $LastLine."$LastLineMember"
                            $Line.Hash = New-Hash -text "$(-join($FirstLine.ID, $LastLineMember))"
                            $AppList += $Line
                        }               
                    }

                }

            }
            $AppList | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
        }
        function Convert-ConfigurationPolicy($Source, $Destination) {
            $AppConfigs_Path = $Source
            $AppList = @()
            Foreach ($entry in Get-ChildItem -Path $AppConfigs_Path) {
             $Line = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json

             $NewHash = New-Hash -text "$(-join($Line.ID, $Line.DisplayName))"
             $Line | Add-Member -MemberType NoteProperty -Name 'Hash' -Value $NewHash -Force
             $AppList += $Line
            }

            $NewHash = New-Hash -text "$(-join($AppList.ID, $AppList.DisplayName))"
            $AppList | Add-Member -MemberType NoteProperty -Name 'Hash' -Value $NewHash -Force
            $AppList | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
        }
        function Convert-EndpointSecurity($Source, $Destination) {
            $AppConfigs_Path = $Source
            $AppList = @()
            Foreach ($Security in Get-ChildItem -Path $Source) {
                Foreach ($Config in Get-ChildItem -Path $Security.Fullname) {
                    $Contents = Get-Content -Path $Config.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json
     
                    Foreach ($Content in $Contents.settingsDelta) {
     
                        $line = '' | Select Name, description, ObjectID, Config, Value, Hash
                        $line.Name = $Contents.displayName
                        $line.description = $Contents.description
                        $line.ObjectID = $Content.id | Out-String
                        $line.Config = try { $Content.definitionId.split('_')[1] }catch { '' }
                        $line.Value = $Content.value | Out-String
                        $Line.Hash = New-Hash -text "$(-join($Line.Name, $Line.ObjectID, $line.Config))"
       
                        $AppList += $line
                    }
     
                }
                $Securityfilename = -join ($Destination, '\EndpointSecurity - ', $Security.Name, '.csv')
                $AppList | Export-Csv -Path $Securityfilename -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
            }
        }
        function Convert-DeviceManagementScript($Source, $Destination) {
            $AppConfigs_Path = $Source
            $AppList = @()
            Foreach ($entry in Get-ChildItem -Path $AppConfigs_Path) {
                $Line = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json | Select-Object displayname, id, description, createdDateTime, lastModifiedDateTime, runAsAccount, fileName
                $NewHash = New-Hash -text "$(-join($AppList.ID, $AppList.DisplayName))"
                $Line | Add-Member -MemberType NoteProperty -Name 'Hash' -Value $NewHash -Force

                $AppList += $Line
            }
            $AppList | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
        }
        function Convert-DeviceEnrollmentStatusPage($Source, $Destination) {
            $AppConfigs_Path = $Source
            $AppList = @()
            Foreach ($entry in Get-ChildItem -Path $AppConfigs_Path) {

                $result = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json | Select-Object priority,
                displayname, 
                id, 
                description, 
                deviceEnrollmentConfigurationType, 
                createdDateTime,
                lastModifiedDateTime,
                showInstallationProgress,
                blockDeviceSetupRetryByUser,
                allowDeviceResetOnInstallFailure,
                allowLogCollectionOnInstallFailure,
                customErrorMessage,
                installProgressTimeoutInMinutes,
                selectedMobileAppIds,
                allowDeviceUseOnInstallFailure,
                trackInstallProgressForAutopilotOnly,
                disableUserStatusTrackingAfterFirstUser
                     
                $AppIDs = $result.selectedMobileAppIds
                $MaxIDs = $AppIDs.Count
                $NrID = 1
                $AssignedApps = @()
                Foreach ($AppID in $AppIDs) {
                    $FoundedApp = $(Get-DeviceAppManagement_MobileApps | Get-MSGraphAllPages | Where-Object { $_.ID -eq $AppID }).displayName
                
                    If ($NrID -eq 1) { $AssignedApps = -join ($FoundedApp, ', ') }
                    elseif ($NrID -eq $MaxIDs) { $AssignedApps = -join ($AssignedApps, $FoundedApp, '') }
                    else {
                        $AssignedApps = -join ($AssignedApps, $FoundedApp, ', ')
                    }   
                    $NrID += 1
                }
                
                $properties = [ordered]@{
                    displayName                             = $result.'displayname'
                    ID                                      = $result.'id'
                    description                             = $result.'description'
                    deviceEnrollmentConfigurationType       = $result.'deviceEnrollmentConfigurationType'
                    createdDateTime                         = $result.'createdDateTime'
                    lastModifiedDateTime                    = $result.'lastModifiedDateTime'
                    showInstallationProgress                = $result.'showInstallationProgress'
                    blockDeviceSetupRetryByUser             = $result.'blockDeviceSetupRetryByUser'
                    allowDeviceResetOnInstallFailure        = $result.'allowDeviceResetOnInstallFailure'
                    allowLogCollectionOnInstallFailure      = $result.'allowLogCollectionOnInstallFailure'
                    customErrorMessage                      = $result.'customErrorMessage'
                    installProgressTimeoutInMinutes         = $result.'installProgressTimeoutInMinutes'
                    minimumSupportedWindowsRelease          = $result.'minimumSupportedWindowsRelease'                                          
                    selectedMobileAppIds                    = If ($AssignedApps) { $AssignedApps }else { '' }
                    allowDeviceUseOnInstallFailure          = $result.'allowDeviceUseOnInstallFailure'
                    trackInstallProgressForAutopilotOnly    = $result.'trackInstallProgressForAutopilotOnly'
                    disableUserStatusTrackingAfterFirstUser = $result.'disableUserStatusTrackingAfterFirstUser'
                    Hash                                    = New-Hash -text "$(-join($result.ID, $result.DisplayName))"

                }
                   
                $AppList += New-Object psobject -Property $properties
            }
            $AppList | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
        }
        function Convert-DeploymentProfiles($Source, $Destination) {
            $AppConfigs_Path = $Source
            $AppList = @()
            Foreach ($entry in Get-ChildItem -Path $AppConfigs_Path) {
                $Line = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json | Select-Object displayname, 
                id,
                description,
                createdDateTime,
                language,
                lastModifiedDateTime,
                enrollmentStatusScreenSettings,
                extractHardwareHash,
                deviceNameTemplate,
                deviceType,
                enableWhiteGlove,
                outOfBoxExperienceSettings

                $NewHash = New-Hash -text "$(-join($AppList.ID, $AppList.DisplayName))"
                $Line | Add-Member -MemberType NoteProperty -Name 'Hash' -Value $NewHash -Force
                $AppList += $Line
            }

            $AppList | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
        }
        function Convert-CatalogSettings($Source, $Destination) {
            function func_PropertyFilter($Property) {
                function func_Deepsearchpropertyfilter($Property) {
                    $List = @()
                    $Members = ($Property | Get-Member).Name
                    If ($Members -match 'choiceSettingValue') {
                        $line = '' | Select Name, Value
                        $line.Name = $Property.settingDefinitionId
               
                        If (($Property.choiceSettingValue.value.GetType()).Name -eq 'Int32') {
                            $line.Value = $Property.choiceSettingValue.value
                        }
                        Elseif ($Property.choiceSettingValue.value.Substring($Property.choiceSettingValue.value.Length - 2) -eq '_1') {
                            $line.Value = 'true'
                        }
                        Elseif ($Property.choiceSettingValue.value.Substring($Property.choiceSettingValue.value.Length - 2) -eq '_0') {
                            $line.Value = 'false'
                        }
                        Else { $line.Value = $Property.choiceSettingValue.value }
               
                        $List += $line
                    }
               
                    If ($Members -match 'simpleSettingValue') {
                        $line = '' | Select Name, Value
                        $line.Name = $Property.settingDefinitionId
               
                        If (($Property.simpleSettingValue.value.GetType()).Name -eq 'Int32') {
                            $line.Value = $Property.simpleSettingValue.value
                        }
                        ElseIf ($Property.simpleSettingValue.value.Substring($Property.simpleSettingValue.value.Length - 2) -eq '_1') {
                            $line.Value = 'true'
                        }
                        Elseif ($Property.simpleSettingValue.value.Substring($Property.simpleSettingValue.value.Length - 2) -eq '_0') {
                            $line.Value = 'false'
                        }
                        Else {
                            $line.Value = $Property.simpleSettingValue.value
               
                        }
               
                        $List += $line
                    }
                    return $List
                }
              
                $MasterList = @()
                If ($Property.choiceSettingValue.children) {
                    func_PropertyFilter -Property $Property.choiceSettingValue.children
                }
                else { 
               
                    If ($Property.settingDefinitionId.Count -ge 2) {
                        Foreach ($entry in $Property) {
                            $MasterList += func_Deepsearchpropertyfilter -Property $entry
                        }
                    }
                    else { $MasterList += func_Deepsearchpropertyfilter -Property $Property }
               
                }
                return $MasterList
            }
             
            $AppList = @()
            Foreach ($entry in Get-ChildItem -Path $Source) {
                $SettingList = @()
                $SettingList = Get-Content -Path $entry.FullName -ErrorAction SilentlyContinue | ConvertFrom-Json
             
                $ConfigSettingList = @()
                Foreach ($Setting in $SettingList) {
                    $ConfigSettingList += func_PropertyFilter -Property $Setting.settings.settingInstance
             
                    Foreach ($ConfigSettinEntry in $ConfigSettingList) {
                        $Line = '' | Select Name, ID, CreatedDateTime, LastModifiedDateTime, Property, Value, Hash
                        $Line.Name = $Setting.name
                        $Line.ID = $Setting.id
                        $Line.CreatedDateTime = $Setting.createdDateTime
                        $Line.LastModifiedDateTime = $Setting.lastModifiedDateTime
                        $Line.Property = $ConfigSettinEntry.Name
                        $Line.Value = $ConfigSettinEntry.Value
                        $Line.Hash = New-Hash -text "$(-join($Setting.ID, $ConfigSettinEntry.Name))"

                        $AppList += $Line
                    }
                }
             
            }
            $AppList | Export-Csv -Path $Destination -NoClobber -NoTypeInformation -Delimiter ';' -Encoding UTF8 -ErrorAction SilentlyContinue
        }

        #Apps
        If ($Joblist.chk_Apps -eq $true) {
            Try {
                Write-Status -Text 'Apps converting...'
                Convert-Apps -Source "$Path\Client Apps" -Destination "$Path\Apps.csv"
            }
            catch { Write-Status -Text 'Apps converting ERROR' }
        }

        #App Assignment
        If ($Joblist.chk_AppAssignment -eq $true) {
            Try {
                Write-Status -Text 'App Assignments converting...'
                $Command = 'mobileAppId'
                Convert-Assignments -Source "$Path\Client Apps\Assignments" -Command $Command -Destination "$Path\AppsAssignment.csv"
            }
            catch { Write-Status -Text 'App Assignments converting ERROR' }
        }

        #Deployment Profiles
        If ($Joblist.chk_Deployment -eq $true) {
            Try {
                Write-Status -Text 'Deployment Profiles converting...'
                Convert-DeploymentProfiles -Source "$Path\DeploymentProfiles" -Destination "$Path\DeploymentProfiles.csv"
            }
            Catch { Write-Status -Text 'Deployment Profiles converting ERROR' }
        }
       
        #Device Compliance Policies
        If ($Joblist.chk_DeviceCompliancePolicies -eq $true) {
            Try {
                Write-Status -Text 'Device Compliance Policies converting...'
                Convert-DeviceCompliancePolicy -Source "$Path\Device Compliance Policies" -Destination "$Path\DeviceCompliancePolicy.csv"
            }
            catch { Write-Status -Text 'Device Compliance Policies converting ERROR' }
        }
   
        #Device Compliance Policies Assignments
        If ($Joblist.chk_DeviceCompliancePolicyAssignment -eq $true) {
            Try {
                Write-Status -Text 'Device Compliance Policies Assignments converting...'
                $Command = 'deviceCompliancePolicyId'
                Convert-Assignments -Source "$path\Device Compliance Policies\Assignments" -Command $Command -Destination "$Path\deviceCompliancePolicyAssignment.csv"
            }
            catch { Write-Status -Text 'Device Compliance Policies Assignments converting ERROR' }
        }

        #Download Settings Catalog
        If ($Joblist.chk_SettingsCatalog -eq $true) {
            Try {
                Write-Status -Text 'Settings Catalog converting...'
                Convert-CatalogSettings -Source "$Path\Settings Catalog" -Destination "$Path\SettingsCatalog.csv"
            }
            Catch { Write-Status -Text 'Settings Catalog converting ERROR' }
        }

        #Download Settings Catalog Assignments
        If ($Joblist.chk_SettingsCatalogAssignment -eq $true) {
            Try {
                Write-Status -Text 'Settings Catalog Assignments converting...'
                $Command = 'id'
                Convert-Assignments -Source "$Path\Settings Catalog\Assignments" -Command $Command -Destination "$Path\SettingsCatalogAssignment.csv"
            }
            Catch { Write-Status -Text 'Settings Catalog Assignments converting ERROR' }
        }

        #Device Configurations
        If ($Joblist.chk_DeviceConfigurations -eq $true) {
            Try {
                Write-Status -Text 'Device Configurations converting...'
                Convert-DeviceConfigurations -Source "$Path\Device Configurations" -Destination "$Path\DeviceConfigurations.csv"
            }
            catch { Write-Status -Text 'Device Configurations converting ERROR' }
        }

        #Device Configurations Assignments
        If ($Joblist.chk_DeviceConfigurationAssignments -eq $true) {
            Try {
                Write-Status -Text 'Device Configurations Assignments converting...'
                $Command = 'deviceConfigurationId'
                Convert-Assignments -Source "$Path\Device Configurations\Assignments" -Command $Command -Destination "$Path\DeviceConfigurationsAssignments.csv"
            }
            catch { Write-Status -Text 'Device Configurations Assignments converting ERROR' }
        }

        #Device Enrollment Status Page
        If ($Joblist.chk_DeviceEnrollmentStatusPage -eq $true) {
            Try {
                Write-Status -Text 'Device Enrollment Status Page converting...'
                Convert-DeviceEnrollmentStatusPage -Source "$Path\DeviceEnrollment" -Destination "$Path\DeviceEnrollmentStatusPage.csv"
            }
            catch { Write-Status -Text 'Device Enrollment Status Page converting ERROR' }
        }
            
        #Device Management Scripts
        If ($Joblist.chk_DeviceManagementScripts -eq $true) {
            Try {
                Write-Status -Text 'Device Management Scripts converting...'
                Convert-DeviceManagementScript -Source "$Path\Device Management Scripts" -Destination "$Path\DeviceManagementScripts.csv"
            }
            catch { Write-Status -Text 'Device Management Scripts converting ERROR' }
        }

        #Device Management Scripts Assignments
        If ($Joblist.chk_DeviceManagementScriptAssignments -eq $true) {
            Try {
                Write-Status -Text 'Device Configurations Assignments converting...'
                $Command = 'id'
                Convert-Assignments -Source "$Path\Device Management Scripts\Assignments" -Command $Command -Destination "$Path\DeviceManagementScriptsAssignments.csv"
            }
            catch { Write-Status -Text 'Device Configurations Assignments converting ERROR' }
        }

        #Endpoint Security
        If ($Joblist.chk_EndpointSecurity -eq $true) {
            Try {
                Write-Status -Text 'Endpoint Security converting...'
                Convert-EndpointSecurity -Source "$Path\EndpointSecurity" -Destination "$Path"
            }
            Catch { Write-Status -Text 'Endpoint Security converting ERROR' }
        }

        Write-Status -Text 'Convert completed !'

    }
    function Cleoni-Merge($Path, $tempFolder, $Filename) {
   
        Write-Status -Text 'CSV to XLSX converting...'

        $csvs = Get-ChildItem -Path "$Path\$tempFolder\*.csv"

        Foreach ($csv in $csvs) {
            $ConvertCSVName = $(($csv.Name).replace('.csv', '').replace('EndpointSecurity', 'ES'))
            If ($ConvertCSVName.length -gt 30) { $ConvertCSVName = $ConvertCSVName.Substring(0, 30) }
            $ConvertCSVName = $ConvertCSVName.trim()
                        
            Import-csv -Path $csv.FullName -Delimiter ';' | Export-Excel -Path "$Path\$Filename" -WorksheetName $ConvertCSVName -Append -AutoSize
            
        }

        Write-Status -Text 'Convert to XLSX complete !'
    
    }
    function Cleoni-Clear($Path) {
        Remove-Item -Path $Path -Confirm:$false -Recurse -Force -ErrorAction SilentlyContinue | Out-Null
        Remove-Item -Path $Path -Confirm:$false -Force -ErrorAction SilentlyContinue | Out-Null
    }

    Write-Status -Text $( -join ('Process-ID: ', $PID)).Trim()
    $PID_Path = "$Path\$tempFolder"
    If (!(Test-Path -Path $PID_Path)) { New-Item -Path $PID_Path -ItemType Directory | out-null }
    $PID | Out-File -FilePath "$PID_Path\PID.txt" -Encoding utf8 -Force | out-null
    
    Write-Status -Text 'Modules checking...'
    $MaximumFunctionCount = 10000
    Module-Install
    
    Write-Status -Text 'MSGraph Login...'
    $Conn = Connect-MSGraph

    #Verbindung prüfen und Skript starten
    try {
        If ($Conn.UPN) {
            Disconnect-MgGraph | Out-Null
            Connect-MgGraph –Scopes “User.Read.All”,”Group.Read.All” | Out-Null

            Cleoni-Download -Path "$Path\$tempFolder" -Joblist $Joblist
            Cleoni-Convert -Path "$Path\$tempFolder" -Joblist $Joblist
            Cleoni-Merge -Path $Path -tempFolder $tempFolder -Filename $Filename
            Cleoni-Clear -Path "$Path\$tempFolder"
        }
    }
    catch [Microsoft.Open.Azure.AD.CommonLibrary.AadNeedAuthenticationException] { }
}