Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
335 changes: 335 additions & 0 deletions IntunePolicyImportExport/CompliancepolicyExport.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,335 @@

Function GenerateFilePath
{

$currentdate = get-date -uformat "%Y-%m-%d_%H.%M.%S"
$LogFilePath = ([Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath) + "\IntuneCompliancePolicyExport_SH_" + $currentdate

$FileExists = Test-Path $LogFilePath

if ($FileExists -eq $False){New-Item $LogFilePath -type directory}



}
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
.EXAMPLE
Get-AuthToken
Authenticates you with the Graph API interface
.NOTES
NAME: Get-AuthToken
#>

[cmdletbinding()]
param
(
[Parameter(Mandatory=$true)]
$User
)

$userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $User

$tenant = $userUpn.Host
Import-Module AzureAD
$AadModule = Get-Module -Name "AzureAD" -ListAvailable
$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 = "XXXXXXXXXXXXXXXXX" #Microsoft Intune Powershell clientID

$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
Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red
Write-Host
break

}

}

catch {

write-host $_.Exception.Message -f Red
write-host $_.Exception.ItemName -f Red
write-host
break

}

}

####################################################

Function Get-DeviceCompliancePolicy(){



[cmdletbinding()]

param
(
[switch]$Android,
[switch]$iOS,
[switch]$Win10
)

$graphApiVersion = "beta"
$Resource = "deviceManagement/deviceCompliancePolicies"

try {

$Count_Params = 0

if($Android.IsPresent){ $Count_Params++ }
if($iOS.IsPresent){ $Count_Params++ }
if($Win10.IsPresent){ $Count_Params++ }

if($Count_Params -gt 1){

write-host "Multiple parameters set, specify a single parameter -Android -iOS or -Win10 against the function" -f Red

}

elseif($Android){

$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value | Where-Object { ($_.'@odata.type').contains("android") }

}

elseif($iOS){

$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value | Where-Object { ($_.'@odata.type').contains("ios") }

}

elseif($Win10){

$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value | Where-Object { ($_.'@odata.type').contains("windows10CompliancePolicy") }

}

else {

$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(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 Export-JSONData(){

<#
.SYNOPSIS
This function is used to export JSON data returned from Graph
.DESCRIPTION
This function is used to export JSON data returned from Graph
.EXAMPLE
Export-JSONData -JSON $JSON
Export the JSON inputted on the function
.NOTES
NAME: Export-JSONData
#>

param (

$JSON,
$ExportPath

)

try {

if($JSON -eq "" -or $JSON -eq $null){

write-host "No JSON specified, please specify valid JSON..." -f Red

}

elseif(!$ExportPath){

write-host "No export path parameter set, please provide a path to export the file" -f Red

}

elseif(!(Test-Path $ExportPath)){

write-host "$ExportPath doesn't exist, can't export JSON Data" -f Red

}

else {

$JSON1 = ConvertTo-Json $JSON -Depth 5

$JSON_Convert = $JSON1 | ConvertFrom-Json

$displayName = $JSON_Convert.displayName

# Updating display name to follow file naming conventions - https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
$DisplayName = $DisplayName -replace '\<|\>|:|"|/|\\|\||\?|\*', "_"

$Properties = ($JSON_Convert | Get-Member | ? { $_.MemberType -eq "NoteProperty" }).Name

$FileName_CSV = "$DisplayName" + ".csv"
$FileName_JSON = "$DisplayName" + ".json"

$Object = New-Object System.Object

foreach($Property in $Properties){

$Object | Add-Member -MemberType NoteProperty -Name $Property -Value $JSON_Convert.$Property

}

write-host "Export Path:" "$ExportPath"

#$Object | Export-Csv -LiteralPath "$ExportPath\$FileName_CSV" -Delimiter "," -NoTypeInformation -Append #export CSV file
$JSON1 | Set-Content -LiteralPath "$ExportPath\$FileName_JSON"
write-host "CSV created in $ExportPath\$FileName_CSV..." -f cyan
write-host "JSON created in $ExportPath\$FileName_JSON..." -f cyan

}

}

catch {

$_.Exception

}

}

####################################################

#region Authentication

write-host

# 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
write-host

# Defining User Principal Name if not present

if($User -eq $null -or $User -eq ""){

$User = Read-Host -Prompt "Please specify your user principal name for Azure Authentication"
Write-Host

}

$global:authToken = Get-AuthToken -User $User

}
}

# Authentication doesn't exist, calling Get-AuthToken function

else {

if($User -eq $null -or $User -eq ""){

$User = Read-Host -Prompt "Please specify your user principal name for Azure Authentication"
Write-Host

}

# Getting the authorization token
$global:authToken = Get-AuthToken -User $User

}

#endregion

####################################################


$ExportPath = GenerateFilePath
$CPs = Get-DeviceCompliancePolicy

foreach($CP in $CPs){

write-host "Device Compliance Policy:"$CP.displayName -f Yellow
Export-JSONData -JSON $CP -ExportPath "$ExportPath"
Write-Host

}
Loading