-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathasd-ioscomp-get.ps1
More file actions
693 lines (610 loc) · 29.4 KB
/
Copy pathasd-ioscomp-get.ps1
File metadata and controls
693 lines (610 loc) · 29.4 KB
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
<#
.SYNOPSIS
Check Intune iOS Compliance Policy settings against ASD Blueprint requirements
.DESCRIPTION
This script checks Intune iOS/iPadOS Compliance Policies against the ASD Blueprint baseline
defined in JSON (default sourced from GitHub). It compares each policy's settings and
reports PASS/FAIL per setting. Generates an HTML report and optional CSV export.
Baseline example (ios-compliance.json):
{
"@odata.type": "#microsoft.graph.iosCompliancePolicy",
"passcodeRequired": true,
"passcodeBlockSimple": true,
"passcodeMinimumLength": 15,
...
}
.EXAMPLE
.\asd-ioscomp-get.ps1
Connects to Microsoft Graph, downloads the latest iOS compliance baseline from GitHub,
checks settings, and generates an HTML report in the parent directory.
.EXAMPLE
.\asd-ioscomp-get.ps1 -ExportToCSV
Also exports results to CSV in the parent directory.
.EXAMPLE
.\asd-ioscomp-get.ps1 -BaselinePath "C:\Baselines\ios-compliance.json"
Uses a custom baseline JSON file.
.NOTES
Author: CIAOPS
Date: 11-25-2025
Version: 1.0
Requirements:
- Microsoft.Graph.DeviceManagement PowerShell module
- Permissions: DeviceManagementConfiguration.Read.All or Global Reader
- Internet connection when using GitHub baseline
Default Baseline:
https://raw.githubusercontent.com/directorcia/bp/main/Intune/Policies/ASD/ios-compliance.json
.LINK
https://github.com/directorcia/office365
https://github.com/directorcia/Office365/wiki/ASD-iOS-Compliance-Policy-Check - Documentation
https://blueprint.asd.gov.au/configuration/intune/device-compliance/
#>
[CmdletBinding()]
param(
[switch]$ExportToCSV,
[string]$CSVPath,
[Parameter(HelpMessage = "Path or URL to baseline JSON file. Defaults to GitHub URL for latest ASD Blueprint settings")]
[string]$BaselinePath,
[Parameter(HelpMessage = "Enable detailed logging to file")]
[switch]$DetailedLogging,
[Parameter(HelpMessage = "Path to log file. Defaults to parent directory with timestamp")]
[string]$LogPath,
[Parameter(HelpMessage = "Custom output path for HTML compliance report. Defaults to timestamped file in parent directory.")]
[Alias('OutputPath')]
[string]$HTMLPath,
[Parameter(HelpMessage = "Target a specific compliance policy by display name. If not specified, all iOS compliance policies are checked.")]
[string]$PolicyName,
[Parameter(HelpMessage = "Skip opening the generated report in the browser")]
[switch]$NoBrowser,
[Parameter(HelpMessage = "Skip automatic installation of missing Microsoft Graph modules")]
[switch]$SkipModuleInstall
)
# Paths
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$parentPath = Split-Path -Parent $scriptPath
function Resolve-OutputPath {
param(
[string]$Path,
[string]$DefaultName
)
if ([string]::IsNullOrWhiteSpace($Path)) {
return Join-Path $parentPath $DefaultName
}
if ([IO.Path]::IsPathRooted($Path)) {
$resolvedPath = $Path
}
else {
$resolvedPath = Join-Path $parentPath $Path
}
$folder = Split-Path -Parent $resolvedPath
if ($folder -and -not (Test-Path $folder)) {
New-Item -ItemType Directory -Path $folder -Force | Out-Null
}
return $resolvedPath
}
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
if (-not $CSVPath) { $CSVPath = "asd-ioscomp-get-$timestamp.csv" }
if ($DetailedLogging -and -not $LogPath) { $LogPath = "asd-ioscomp-get-$timestamp.log" }
# Default GitHub URL for baseline settings
$defaultGitHubURL = "https://raw.githubusercontent.com/directorcia/bp/main/Intune/Policies/ASD/ios-compliance.json"
if (-not $BaselinePath) { $BaselinePath = $defaultGitHubURL }
# Script-scope state
$script:BaselinePath = $BaselinePath
$script:baselineLoaded = $false
$script:HTMLPath = Resolve-OutputPath -Path $HTMLPath -DefaultName "asd-ioscomp-get-$timestamp.html"
$script:CSVPath = Resolve-OutputPath -Path $CSVPath -DefaultName "asd-ioscomp-get-$timestamp.csv"
$script:LogPath = if ($DetailedLogging) { Resolve-OutputPath -Path $LogPath -DefaultName "asd-ioscomp-get-$timestamp.log" } else { $null }
$script:DetailedLogging = $DetailedLogging
$script:connectedDomain = "Unknown"
$scriptVersion = "1.0"
$scriptName = "ASD iOS Compliance Policy Check"
# Logging
function Write-Log {
param([string]$Message,[string]$Level = "INFO")
if ($script:DetailedLogging -and $script:LogPath) {
try { $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"; Add-Content -Path $script:LogPath -Value "[$ts] [$Level] $Message" -ErrorAction Stop } catch { }
}
}
# Console color output
function Write-ColorOutput {
param([string]$Message,[string]$Type = "Info")
$level = switch($Type){"Success"{"INFO"}"Warning"{"WARN"}"Error"{"ERROR"}default{"INFO"}}
Write-Log -Message $Message -Level $level
switch($Type){
"Success" { Write-Host $Message -ForegroundColor Green }
"Warning" { Write-Host $Message -ForegroundColor Yellow }
"Error" { Write-Host $Message -ForegroundColor Red }
default { Write-Host $Message -ForegroundColor Cyan }
}
}
# Baseline loader
function Test-BaselineSchema {
param([object]$Baseline)
# Expect: Root object with @odata.type and compliance settings properties
if ($null -eq $Baseline) { return $false }
if (-not $Baseline.'@odata.type') { return $false }
if ($Baseline.'@odata.type' -notlike '*iosCompliancePolicy*') { return $false }
return $true
}
function Get-BaselineSettings {
param([string]$Path)
Write-Log "Loading baseline from: $Path"
$json = $null
$isUrl = $Path -match '^https?://'
try {
if ($isUrl) {
Write-ColorOutput "Downloading baseline from GitHub..." -Type Info
$content = (Invoke-WebRequest -Uri $Path -UseBasicParsing -ErrorAction Stop).Content
$json = $content | ConvertFrom-Json -ErrorAction Stop
}
elseif (Test-Path $Path) {
Write-ColorOutput "Loading baseline from local file..." -Type Info
$json = Get-Content -Path $Path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
}
else {
Write-ColorOutput "Baseline not found at path: $Path" -Type Warning
return $null
}
}
catch {
Write-ColorOutput "Failed to load/parse baseline JSON: $($_.Exception.Message)" -Type Error
return $null
}
if (-not (Test-BaselineSchema -Baseline $json)) {
Write-ColorOutput "Baseline JSON schema validation failed. Expecting iOS Compliance Policy JSON." -Type Error
return $null
}
$script:baselineLoaded = $true
return $json
}
# Graph module & connection
function Install-GraphModule {
param([switch]$SkipInstall)
$moduleName = 'Microsoft.Graph.Authentication'
if (Get-Module -ListAvailable -Name $moduleName) {
return $true
}
if ($SkipInstall) {
Write-ColorOutput "Missing module $moduleName and automatic installation was skipped." -Type Warning
return $false
}
Write-ColorOutput "Installing missing Microsoft Graph module..." -Type Info
try {
if (Get-Command Install-Module -ErrorAction SilentlyContinue) {
Install-Module -Name $moduleName -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop
}
elseif (Get-Command Install-PSResource -ErrorAction SilentlyContinue) {
Install-PSResource -Name $moduleName -Scope CurrentUser -TrustRepository -ErrorAction Stop
}
else {
throw 'Neither Install-Module nor Install-PSResource is available.'
}
Write-ColorOutput "Microsoft Graph module installed successfully." -Type Success
return $true
}
catch {
Write-ColorOutput "Failed to install Microsoft.Graph.Authentication: $($_.Exception.Message)" -Type Error
Write-ColorOutput "Install it manually with: Install-Module Microsoft.Graph -Scope CurrentUser" -Type Warning
return $false
}
}
function Test-GraphModule {
Write-ColorOutput "Checking for Microsoft.Graph modules..." -Type Info
try {
if (-not (Get-Module -ListAvailable -Name 'Microsoft.Graph.Authentication')) {
if (-not (Install-GraphModule -SkipInstall:$SkipModuleInstall)) {
return $false
}
}
Import-Module Microsoft.Graph.Authentication -ErrorAction Stop | Out-Null
Write-ColorOutput "Microsoft.Graph.Authentication module loaded." -Type Success
return $true
}
catch {
Write-ColorOutput "Failed to load Microsoft.Graph.Authentication module: $($_.Exception.Message)" -Type Error
Write-ColorOutput "Install with: Install-Module Microsoft.Graph -Scope CurrentUser" -Type Warning
return $false
}
}
function Connect-MSGraph {
param([switch]$ForceReconnect)
Write-ColorOutput "`nChecking Microsoft Graph connection..." -Type Info
try {
# Check if already connected
$context = Get-MgContext -ErrorAction SilentlyContinue
if ($context -and -not $ForceReconnect) {
Write-ColorOutput "Already connected to Microsoft Graph." -Type Success
Write-ColorOutput "Tenant: $($context.TenantId)" -Type Info
# Check if we have the required scope
$requiredScope = "DeviceManagementConfiguration.Read.All"
if ($context.Scopes -notcontains $requiredScope) {
Write-ColorOutput "`nWarning: Current connection missing required permission: $requiredScope" -Type Warning
Write-ColorOutput "Disconnecting and reconnecting with correct permissions..." -Type Info
Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
Start-Sleep -Seconds 1
} else {
# Get organization domain
try {
$orgUrl = "https://graph.microsoft.com/v1.0/organization"
$org = Invoke-MgGraphRequest -Method GET -Uri $orgUrl -ErrorAction Stop
if ($org.value -and $org.value.Count -gt 0) {
$domain = $org.value[0].verifiedDomains | Where-Object { $_.isDefault -eq $true } | Select-Object -ExpandProperty name
if ($domain) {
$script:connectedDomain = $domain
Write-ColorOutput "Domain: $domain" -Type Info
}
}
} catch {
Write-Log "Failed to retrieve organization domain: $($_.Exception.Message)" -Level WARN
}
return $true
}
}
elseif ($ForceReconnect -and $context) {
Write-ColorOutput "Force reconnect requested. Disconnecting..." -Type Info
Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
Start-Sleep -Seconds 1
}
Write-ColorOutput "Connecting to Microsoft Graph..." -Type Info
Connect-MgGraph -Scopes "DeviceManagementConfiguration.Read.All" -NoWelcome -ErrorAction Stop
Write-ColorOutput "Connected to Microsoft Graph." -Type Success
# Get organization domain after connecting
try {
$orgUrl = "https://graph.microsoft.com/v1.0/organization"
$org = Invoke-MgGraphRequest -Method GET -Uri $orgUrl -ErrorAction Stop
if ($org.value -and $org.value.Count -gt 0) {
$domain = $org.value[0].verifiedDomains | Where-Object { $_.isDefault -eq $true } | Select-Object -ExpandProperty name
if ($domain) {
$script:connectedDomain = $domain
Write-ColorOutput "Domain: $domain" -Type Info
}
}
} catch {
Write-Log "Failed to retrieve organization domain: $($_.Exception.Message)" -Level WARN
}
return $true
}
catch {
Write-ColorOutput "Failed to connect to Microsoft Graph: $($_.Exception.Message)" -Type Error
return $false
}
}
function Test-GraphPermissions {
Write-ColorOutput "`nValidating Microsoft Graph permissions..." -Type Info
try {
$url = "https://graph.microsoft.com/beta/deviceManagement/deviceCompliancePolicies?`$top=1"
$null = Invoke-MgGraphRequest -Method GET -Uri $url -ErrorAction Stop
Write-ColorOutput "Permission validation passed." -Type Success
return $true
}
catch {
Write-ColorOutput "Permission validation failed: $($_.Exception.Message)" -Type Error
Write-ColorOutput "Required permission: DeviceManagementConfiguration.Read.All" -Type Warning
# Check if this is a permission issue (BadRequest often means insufficient permissions)
if ($_.Exception.Message -like "*BadRequest*" -or $_.Exception.Message -like "*Forbidden*" -or $_.Exception.Message -like "*Unauthorized*") {
Write-ColorOutput "`nInsufficient permissions detected. Attempting to reconnect with correct scope..." -Type Warning
# Try to reconnect with the required permission
$reconnected = Connect-MSGraph -ForceReconnect
if ($reconnected) {
Write-ColorOutput "`nRetrying permission validation..." -Type Info
try {
$null = Invoke-MgGraphRequest -Method GET -Uri $url -ErrorAction Stop
Write-ColorOutput "Permission validation passed after reconnection." -Type Success
return $true
}
catch {
Write-ColorOutput "Permission validation still failed: $($_.Exception.Message)" -Type Error
Write-ColorOutput "`nYou may need to grant admin consent for the app in Azure AD." -Type Warning
Write-ColorOutput "Required permission: DeviceManagementConfiguration.Read.All" -Type Warning
return $false
}
}
}
return $false
}
}
# Comparison helpers
function Convert-ToComparableValue {
param([object]$Value)
if ($null -eq $Value) { return $null }
if ($Value -is [bool]) { return [bool]$Value }
# Handle arrays (like scheduledActionsForRule, validOperatingSystemBuildRanges)
if ($Value -is [array]) {
if ($Value.Count -eq 0) { return "[]" }
return ($Value | ConvertTo-Json -Compress)
}
# Trim and normalize strings; treat "True"/"False" as booleans when possible
$s = $Value.ToString().Trim()
if ($s -match '^(?i:true|false)$') { return [System.Convert]::ToBoolean($s) }
return $s
}
function Compare-Values {
param([object]$Current,[object]$Required)
$c = Convert-ToComparableValue $Current
$r = Convert-ToComparableValue $Required
if ($null -eq $r -and $null -eq $c) { return $true }
if ($null -eq $r) { return $true }
# Special handling for arrays
if ($r -is [string] -and $r.StartsWith('[') -and $r.EndsWith(']')) {
if ($c -is [string] -and $c.StartsWith('[') -and $c.EndsWith(']')) {
return ($c -eq $r)
}
return $false
}
if ($c -is [bool] -and $r -is [bool]) { return ($c -eq $r) }
# case-insensitive for strings
return ("$c" -ieq "$r")
}
function Test-Setting {
param(
[string]$PolicyName,
[string]$SettingName,
[object]$CurrentValue,
[object]$RequiredValue
)
$cur = if ($null -eq $CurrentValue) { "Not set" } else { $CurrentValue.ToString() }
$req = if ($null -eq $RequiredValue) { "Not set" } else { $RequiredValue.ToString() }
$ok = Compare-Values -Current $CurrentValue -Required $RequiredValue
Write-Log "Check [$PolicyName] $SettingName - Current: $cur, Required: $req, Status: $(if($ok){'PASS'}else{'FAIL'})" -Level $(if($ok){'INFO'}else{'WARN'})
[pscustomobject]@{
Policy = $PolicyName
Setting = $SettingName
CurrentValue = $cur
RequiredValue= $req
Compliant = $ok
Status = if ($ok) { 'PASS' } else { 'FAIL' }
}
}
# HTML report
function New-HTMLReport {
param([array]$CheckResults,[string]$OutputPath)
$total = $CheckResults.Count
$passed = ($CheckResults | Where-Object { $_.Compliant }).Count
$failed = $total - $passed
$pct = if ($total -gt 0) { [math]::Round(($passed/$total)*100,2) } else { 0 }
$overall = if ($pct -eq 100) { 'COMPLIANT' } else { 'NON-COMPLIANT' }
$statusColor = if ($pct -eq 100) { '#28a745' } else { '#dc3545' }
$reportDate = Get-Date -Format "dd MMMM yyyy - HH:mm:ss"
$domainInfo = if ($script:connectedDomain -and $script:connectedDomain -ne "Unknown") { $script:connectedDomain } else { "Unknown" }
$html = @"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ASD iOS Compliance Policy Report</title>
<style>
body{font-family:'Segoe UI',Tahoma,Verdana,sans-serif;background:#f0f2f5;padding:20px}
.container{max-width:1200px;margin:0 auto;background:#fff;border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.15);overflow:hidden}
.header{background:linear-gradient(135deg,#1e3c72,#2a5298);color:#fff;padding:30px;text-align:center}
.summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:20px;padding:20px;background:#f8f9fa}
.card{background:#fff;padding:18px;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.08);text-align:center;transition:transform .3s ease}
.card:hover{transform:translateY(-4px);box-shadow:0 6px 18px rgba(0,0,0,.12)}
.card .value{font-size:2.2em;font-weight:700}
.card.total .value{color:#007bff}
.card.passed .value{color:#28a745}
.card.failed .value{color:#dc3545}
.card.compliance .value{color:$statusColor}
.results{padding:25px}
table{width:100%;border-collapse:collapse}
thead{background:linear-gradient(135deg,#1e3c72,#2a5298);color:#fff}
th,td{padding:12px 14px;border-bottom:1px solid #e9ecef;text-align:left}
tbody tr:nth-child(even){background:#f8f9fa}
.badge{display:inline-block;padding:4px 10px;border-radius:14px;font-weight:600}
.pass{background:#d4edda;color:#155724;border:1px solid #c3e6cb}
.fail{background:#f8d7da;color:#721c24;border:1px solid #f5c6cb}
.overall{background:$statusColor;color:#fff;text-align:center;padding:24px}
.footer{padding:20px;text-align:center;background:#f8f9fa;color:#6c757d;font-size:.9em;border-top:1px solid #e9ecef}
.footer a{color:#2a5298;text-decoration:none;font-weight:700}
.footer a:hover{text-decoration:underline}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🛡️ ASD iOS Compliance Policy Report</h1>
<p>Domain: $domainInfo</p>
<p>Generated: $reportDate</p>
</div>
<div class="summary">
<div class="card total"><div>Total Checks</div><div class="value">$total</div></div>
<div class="card passed"><div>Passed</div><div class="value">$passed</div></div>
<div class="card failed"><div>Failed</div><div class="value">$failed</div></div>
<div class="card compliance"><div>Compliance</div><div class="value">$pct%</div></div>
</div>
<div class="results">
<table>
<thead><tr><th>Status</th><th>Policy</th><th>Setting</th><th>Current</th><th>Required</th></tr></thead>
<tbody>
"@
foreach ($r in $CheckResults) {
$cls = if ($r.Compliant) { 'pass' } else { 'fail' }
$txt = if ($r.Compliant) { 'PASS' } else { 'FAIL' }
$html += @"
<tr>
<td><span class="badge $cls">$txt</span></td>
<td><strong>$($r.Policy)</strong></td>
<td>$($r.Setting)</td>
<td>$($r.CurrentValue)</td>
<td>$($r.RequiredValue)</td>
</tr>
"@
}
$html += @"
</tbody>
</table>
</div>
<div class="overall"><h2>Overall Status: $overall</h2>
<p style="font-size:1.1em;margin-top:8px;">$passed of $total checks passed</p>
</div>
<div class="footer">
<p><strong>Reference:</strong> <a href="https://blueprint.asd.gov.au/configuration/intune/devices/compliance-policies/policies/apple-ios-and-ipad/" target="_blank">ASD's Blueprint for Secure Cloud - iOS Device Compliance</a></p>
<p style="margin-top:10px;"><strong>Security Controls:</strong> <a href="https://github.com/directorcia/bp/wiki/iOS-Compliance-Policy-Settings-%E2%80%90-Security-Rationale" target="_blank">Why These Recommendations Matter</a></p>
</div>
</div>
</body>
</html>
"@
try { $html | Out-File -FilePath $OutputPath -Encoding UTF8 -Force; return $true }
catch { Write-ColorOutput "Failed to generate HTML report: $($_.Exception.Message)" -Type Error; return $false }
}
# Main check
function Invoke-CompliancePolicyCheck {
param([psobject]$Requirements, [string]$TargetPolicyName)
Write-ColorOutput "`n========================================" -Type Info
Write-ColorOutput " $scriptName v$scriptVersion" -Type Info
Write-ColorOutput " ASD Blueprint Compliance Check" -Type Info
Write-ColorOutput "========================================`n" -Type Info
Write-ColorOutput "Retrieving iOS compliance policies from Intune..." -Type Info
try {
# Use Graph API directly to avoid module loading conflicts
$url = "https://graph.microsoft.com/beta/deviceManagement/deviceCompliancePolicies"
$response = Invoke-MgGraphRequest -Method GET -Uri $url -ErrorAction Stop
$allPolicies = $response.value
# Handle pagination if needed
while ($response.'@odata.nextLink') {
$response = Invoke-MgGraphRequest -Method GET -Uri $response.'@odata.nextLink' -ErrorAction Stop
$allPolicies += $response.value
}
# Filter for iOS compliance policies
$policies = $allPolicies | Where-Object {
$_.'@odata.type' -eq '#microsoft.graph.iosCompliancePolicy'
}
# Further filter by policy name if specified
if ($TargetPolicyName) {
$policies = $policies | Where-Object { $_.displayName -eq $TargetPolicyName }
if (-not $policies) {
Write-ColorOutput "No iOS compliance policy found with name: $TargetPolicyName" -Type Warning
return $null
}
}
if (-not $policies) {
Write-ColorOutput "No iOS/iPadOS compliance policies found." -Type Warning
return $null
}
Write-ColorOutput "Found $($policies.Count) iOS compliance $(if($policies.Count -eq 1){'policy'}else{'policies'}) to check." -Type Success
}
catch {
Write-ColorOutput "Failed to retrieve compliance policies: $($_.Exception.Message)" -Type Error
return $null
}
$results = @()
# Get baseline settings (excluding metadata fields)
$baselineSettings = ($Requirements | Get-Member -MemberType NoteProperty |
Where-Object { $_.Name -notin @('@odata.type', 'displayName', 'description', 'version', 'scheduledActionsForRule', 'roleScopeTagIds') } |
Select-Object -ExpandProperty Name)
foreach ($policy in $policies) {
$policyName = $policy.displayName
Write-ColorOutput "`nChecking policy: $policyName" -Type Info
# Get full policy details using Graph API
try {
$detailUrl = "https://graph.microsoft.com/beta/deviceManagement/deviceCompliancePolicies/$($policy.id)"
$policyDetails = Invoke-MgGraphRequest -Method GET -Uri $detailUrl -ErrorAction Stop
}
catch {
Write-ColorOutput "Failed to retrieve details for policy: $policyName" -Type Error
continue
}
# Compare each setting in baseline
foreach ($setting in $baselineSettings) {
$required = $Requirements.$setting
$current = $null
# Try to read property directly
try {
$current = $policyDetails.$setting
} catch {
$current = $null
}
# Handle additional properties that might be in AdditionalProperties
if ($null -eq $current -and $policyDetails.AdditionalProperties) {
try {
$current = $policyDetails.AdditionalProperties[$setting]
} catch {
$current = $null
}
}
$results += Test-Setting -PolicyName $policyName -SettingName $setting -CurrentValue $current -RequiredValue $required
}
}
# Output to console
Write-ColorOutput "`n========================================" -Type Info
Write-ColorOutput " CHECK RESULTS" -Type Info
Write-ColorOutput "========================================`n" -Type Info
foreach ($r in $results) {
$type = if ($r.Compliant) { 'Success' } else { 'Error' }
$sym = if ($r.Compliant) { '[✓]' } else { '[✗]' }
Write-ColorOutput "$sym [$($r.Policy)] $($r.Setting)" -Type $type
Write-Host " Current : $($r.CurrentValue)"
Write-Host " Required: $($r.RequiredValue)"
Write-Host " Status : $($r.Status)"
}
$total = $results.Count
$passed = ($results | Where-Object { $_.Compliant }).Count
$failed = $total - $passed
$pct = if ($total -gt 0) { [math]::Round(($passed/$total)*100,2) } else { 0 }
Write-ColorOutput "========================================" -Type Info
Write-ColorOutput " SUMMARY" -Type Info
Write-ColorOutput "========================================" -Type Info
Write-Host "Total Checks : $total"
Write-ColorOutput "Passed : $passed" -Type Success
if ($failed -gt 0) { Write-ColorOutput "Failed : $failed" -Type Error } else { Write-ColorOutput "Failed : $failed" -Type Success }
Write-Host "Compliance : $pct%"
if ($pct -eq 100) { Write-ColorOutput "`nStatus : COMPLIANT ✓" -Type Success } else { Write-ColorOutput "`nStatus : NON-COMPLIANT ✗" -Type Error }
Write-ColorOutput "========================================`n" -Type Info
# CSV export
if ($ExportToCSV) {
try {
$results | Select-Object Policy,Setting,CurrentValue,RequiredValue,Status | Export-Csv -Path $script:CSVPath -NoTypeInformation -Encoding UTF8
Write-ColorOutput "Results exported to: $script:CSVPath" -Type Success
} catch { Write-ColorOutput "Failed to export CSV: $($_.Exception.Message)" -Type Error }
}
# HTML report
Write-ColorOutput "Generating HTML report..." -Type Info
if (New-HTMLReport -CheckResults $results -OutputPath $script:HTMLPath) {
Write-ColorOutput "HTML report generated: $script:HTMLPath" -Type Success
if (-not $NoBrowser) {
try { Start-Process $script:HTMLPath } catch { Write-ColorOutput "Could not open report in browser: $($_.Exception.Message)" -Type Warning }
}
else {
Write-ColorOutput "Browser opening skipped because -NoBrowser was specified." -Type Info
}
}
return $results
}
# Main
try {
if ($script:DetailedLogging) {
Write-Log "=== ASD iOS Compliance Policy Check Started ==="
Write-Log "Script Version: $scriptVersion"
Write-Log "PowerShell Version: $($PSVersionTable.PSVersion)"
Write-Log "Log Path: $script:LogPath"
}
Write-ColorOutput "`n========================================" -Type Info
Write-ColorOutput " ASD iOS Compliance Policy Check" -Type Info
Write-ColorOutput "========================================" -Type Info
$isUrl = $script:BaselinePath -match '^https?://'
if ($isUrl) { Write-ColorOutput "Baseline: GitHub (latest)" -Type Info } elseif (Test-Path $script:BaselinePath) { Write-ColorOutput "Baseline: Local File (found)" -Type Success } else { Write-ColorOutput "Baseline: Local File (not found)" -Type Warning }
Write-ColorOutput "Location: $script:BaselinePath" -Type Info
Write-ColorOutput "Output: $parentPath`n" -Type Info
$baseline = Get-BaselineSettings -Path $BaselinePath
if (-not $baseline) { Write-ColorOutput "Failed to load baseline settings. Cannot proceed." -Type Error; exit 1 }
if (-not (Test-GraphModule)) { Write-ColorOutput "`nMicrosoft.Graph.Authentication module is required." -Type Error; exit 1 }
if (-not (Connect-MSGraph)) { Write-ColorOutput "`nFailed to connect to Microsoft Graph." -Type Error; exit 1 }
if (-not (Test-GraphPermissions)) { Write-ColorOutput "`nInsufficient permissions to read compliance policies." -Type Error; exit 1 }
$null = Invoke-CompliancePolicyCheck -Requirements $baseline -TargetPolicyName $PolicyName
Write-ColorOutput "`nScript completed." -Type Success
}
catch {
Write-Log "SCRIPT EXECUTION FAILED: $($_.Exception.Message)"
Write-ColorOutput "`n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -Type Error
Write-ColorOutput "❌ SCRIPT EXECUTION FAILED" -Type Error
Write-ColorOutput "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -Type Error
Write-Host ""
Write-ColorOutput "Error Message:" -Type Error
Write-Host " $($_.Exception.Message)"
Write-Host ""
Write-ColorOutput "Error Location:" -Type Warning
Write-Host " Line: $($_.InvocationInfo.ScriptLineNumber)"
Write-Host " Command: $($_.InvocationInfo.Line.Trim())"
Write-Host ""
if ($script:DetailedLogging) { Write-Host ""; Write-ColorOutput "Detailed error log saved to: $script:LogPath" -Type Info }
exit 1
}