Framework/Core/SubscriptionSecurity/ARMPolicies.ps1

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
using namespace System.Management.Automation
Set-StrictMode -Version Latest 

# Class to implement Subscription ARM Policy controls
class ARMPolicy: CommandBase
{    
    hidden [ARMPolicyModel] $ARMPolicyObj = $null;
    hidden [PolicyInitiative] $SubPolicyInitiative = $null;
    hidden [bool] $UpdateInitiative = $false;
    static [string] $PolicyProviderNamespace = "Microsoft.PolicyInsights";
    
    hidden [PSObject[]] $ApplicableARMPolicies = $null;
    #hidden [PSObject[]] $PolicyAssignments = $null;

    ARMPolicy([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $tags, [bool] $updateInitiative): 
        Base($subscriptionId, $invocationContext)
    { 
        $this.ARMPolicyObj = [ARMPolicyModel] $this.LoadServerConfigFile("Subscription.ARMPolicies.json"); 
        $isPolicyInitiativeEnabled = [FeatureFlightingManager]::GetFeatureStatus("EnableAzurePolicyBasedScan",$($this.SubscriptionContext.SubscriptionId))
        if($isPolicyInitiativeEnabled)
        {
            $this.SubPolicyInitiative = [PolicyInitiative] $this.LoadServerConfigFile("Subscription.Initiative.json"); 
        }
        $this.FilterTags = $this.ConvertToStringArray($tags);
        $this.UpdateInitiative = $updateInitiative;
    }

    hidden [PSObject[]] GetApplicableARMPolicies()
    {
        if($null -eq $this.ApplicableARMPolicies)
        {
            $this.ApplicableARMPolicies = @();

            $subscriptionId = $this.SubscriptionContext.SubscriptionId;
            if(($this.FilterTags | Measure-Object).Count -ne 0)
            {
                $this.ARMPolicyObj.Policies | 
                    ForEach-Object {
                        $currentItem = $_;
                        if(($currentItem.Tags | Where-Object { $this.FilterTags -Contains $_ } | Measure-Object).Count -ne 0)
                        {
                            # Resolve the value of SubscriptionId
                            $currentItem.Scope = $global:ExecutionContext.InvokeCommand.ExpandString($currentItem.Scope);
                            if([string]::IsNullOrWhiteSpace($currentItem.Scope))
                            {
                                $currentItem.Scope = "/subscriptions/$subscriptionId"
                            }

                            $this.ApplicableARMPolicies  += $currentItem;
                        }
                    }
            }
            else
            {
                $this.ApplicableARMPolicies += $this.ARMPolicyObj.Policies
            }
        }
            
        return $this.ApplicableARMPolicies;
    }

    [MessageData[]] SetARMPolicies()
    {
        [Helpers]::RegisterResourceProviderIfNotRegistered([ARMPolicy]::PolicyProviderNamespace);
        [MessageData[]] $messages = @();
        $this.RemoveDeprecatedPolicies();
        if(($this.ARMPolicyObj.Policies | Measure-Object).Count -ne 0)
        {
            if($this.GetApplicableARMPolicies() -ne 0)
            {
                $startMessage = [MessageData]::new("Processing AzSK ARM policies. Total policies: $($this.GetApplicableARMPolicies().Count)");
                $messages += $startMessage;
                $this.PublishCustomMessage($startMessage);
                $this.PublishCustomMessage("Note: Configuring ARM policies can take about 2-3 min...", [MessageType]::Warning);                

                $disabledPolicies = $this.GetApplicableARMPolicies() | Where-Object { -not $_.Enabled };
                if(($disabledPolicies | Measure-Object).Count -ne 0)
                {
                    $disabledMessage = "Found ARM policies which are disabled. Total disabled policies: $($disabledPolicies.Count)";
                    $messages += [MessageData]::new($disabledMessage, $disabledPolicies);
                    $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
                }

                $enabledPolicies = @();
                $enabledPolicies += $this.GetApplicableARMPolicies() | Where-Object { $_.Enabled };
                if($enabledPolicies.Count -ne 0)
                {
                    $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nAdding following ARM policies to the subscription. Total policies: $($enabledPolicies.Count)", $enabledPolicies);                                                                            
                    $armPoliciesDefns = @{};
                    $enabledPolicies | ForEach-Object {
                        $policyName = $_.PolicyDefinitionName;
                        $armPolicy = $null;
                        try {
                            $armPolicy = Get-AzPolicyDefinition -Name $policyName -ErrorAction Stop
                            try{
                            $temp = $_;        
                            $armpolicyassignment = Get-AzPolicyAssignment -Name $policyName
                            }
                            catch{
                            $armPoliciesDefns.Add($temp,$armPolicy);
                            }
                        }
                        catch {
                            #eat the exception if the policy is not found
                        }
                        if($null -eq $armPolicy)
                        {
                            # Add ARM policy
                            try
                            {
                                $armPolicy = New-AzPolicyDefinition -Name $policyName -Description $_.Description -Policy ([string]$_.PolicyDefinition) -ErrorAction Stop
                                $armPoliciesDefns.Add($_,$armPolicy);
                            }
                            catch
                            {
                                $messages += [MessageData]::new("Error while adding ARM policy [$policyName] to the subscription", $_, [MessageType]::Error);
                            }
                        }                            
                    };
                    $errorCount = 0;
                    $currentCount = 0;
                    if(($armPoliciesDefns.Keys | Measure-Object).Count -gt 0)
                    {
                        Start-Sleep -Seconds 15                                                            
                        $armPoliciesDefns.Keys | ForEach-Object {
                            $armPolicy = $_;
                            $armPolicyDefn = $armPoliciesDefns[$_];
                            $policyName = $armPolicy.PolicyDefinitionName;
                            $currentCount += 1;
                            # Add ARM policy
                            try
                            {                                
                                New-AzPolicyAssignment -Name $policyName -PolicyDefinition $armPolicyDefn  -Scope $armPolicy.Scope -ErrorAction Stop | Out-Null
                            }
                            catch
                            {
                                $messages += [MessageData]::new("Error while adding ARM policy [$policyName] to the subscription", $armPolicy, [MessageType]::Error);
                                $errorCount += 1;
                            }
                            $this.CommandProgress($enabledPolicies.Count, $currentCount, 2);
                        };
                    }
                    [MessageData[]] $resultMessages = @();
                    if($errorCount -eq 0)
                    {
                        #setting the version tag at AzSKRG
                        $azskRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
                        [Helpers]::SetResourceGroupTags($azskRGName,@{[Constants]::ARMPolicyConfigVersionTagName=$this.ARMPolicyObj.Version}, $false)
                    
                    $resultMessages += [MessageData]::new("All AzSK ARM policies have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                    }
                    elseif($errorCount -eq $enabledPolicies.Count)
                    {
                        $resultMessages += [MessageData]::new("No AzSK ARM policies were added to the subscription due to an error. Please add the ARM policies manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error);
                    }
                    else
                    {
                        $resultMessages += [MessageData]::new("$errorCount/$($enabledPolicies.Count) ARM policy(ies) have not been added to the subscription. Please add the ARM policies manually or contact AzSK support team.", [MessageType]::Error);
                        $resultMessages += [MessageData]::new("$($enabledPolicies.Count - $errorCount)/$($enabledPolicies.Count) ARM policy(ies) have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                    }

                    $messages += $resultMessages;
                    $this.PublishCustomMessage($resultMessages);
                }
            }
            else
            {
                $this.PublishCustomMessage("No ARM policies have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning);
            }
        }
        $messages += $this.SetPolicyInitiative();
        return $messages;
    }

    [void] RemoveDeprecatedPolicies()
    {
        if(($this.ARMPolicyObj.DeprecatedPolicies | Measure-Object).Count -gt 0)
        {
            $DeprecatedPolicyDefns = @();
            $this.ARMPolicyObj.DeprecatedPolicies | ForEach-Object {
                try
                {
                    $PolicyName = $_;
                    $PolicyDefn = Get-AzPolicyDefinition -Name $PolicyName -ErrorAction SilentlyContinue
                    if($null -ne $PolicyDefn)
                    {
                        $DeprecatedPolicyDefns += $PolicyDefn;
                    }
                }
                catch
                {
                    #eat this exception as silently continue is not working for this scenario
                }
            }
            if(($DeprecatedPolicyDefns | Measure-Object).Count -gt 0)
            {
                $assignments = @();
                $DeprecatedPolicyDefns | ForEach-Object {
                    $defn = $_;
                    $tassignment = Get-AzPolicyAssignment -PolicyDefinitionId $defn.policyDefinitionId  -ErrorAction SilentlyContinue
                    if($null -ne $tassignment)
                    {
                        $assignments += $tassignment;
                    }
                }
                if(($assignments | Measure-Object).Count -gt 0)
                {
                    $assignments | ForEach-Object {
                        $assigment = $_;
                        Remove-AzPolicyAssignment -Scope $assigment.properties.scope -Name $assigment.Name -ErrorAction SilentlyContinue
                    }                        
                    Start-Sleep -Seconds 15
                }                
                $DeprecatedPolicyDefns | ForEach-Object {
                    try
                    {
                        $defn = $_;
                        Remove-AzPolicyDefinition -Id $defn.PolicyDefinitionId -Force -ErrorAction SilentlyContinue        
                    }
                    catch
                    {
                        #todo eat the exception as it might throw error if it is being used in any of initiatives
                    }
                }                                                            
            }                                                                    
        }
    }

    [void] RemoveDeprecatedInitiatives()
    {
        if($null -ne $this.SubPolicyInitiative -and ($this.SubPolicyInitiative.DeprecatedInitiatives | Measure-Object).Count -gt 0)
        {
            $deprecatedInitiatives = @();
            $this.SubPolicyInitiative.DeprecatedInitiatives | ForEach-Object {
                $depInitiative = $_;
                $deprecatedInitiative = Get-AzPolicySetDefinition -Name $depInitiative -ErrorAction SilentlyContinue
                if($null -ne $deprecatedInitiative)
                {
                    $deprecatedInitiatives += $deprecatedInitiative;
                }                
            }
            if(($deprecatedInitiatives | Measure-Object).Count -gt 0)
            {
                $deprecatedInitiatives | ForEach-Object {
                    $depInitiative = $_;
                    $assignments = @();
                    $tassignment = Get-AzPolicyAssignment -PolicyDefinitionId $depInitiative.PolicySetDefinitionId -ErrorAction SilentlyContinue
                    if(($tassignment | Measure-Object).Count -gt 0)
                    {
                        $assignments += $tassignment
                    }
                    if(($assignments | Measure-Object).Count -gt 0)                    
                    {
                        $assignments | ForEach-Object {                        
                            $assignment = $_;
                            Remove-AzPolicyAssignment -Scope $assignment.Scope -Name $assignment.Name -Force -ErrorAction SilentlyContinue
                        }
                    }
                }

                Start-Sleep -Seconds 15
                $deprecatedInitiatives | ForEach-Object {
                    $depInitiative = $_;
                    Remove-AzPolicySetDefinition -Name $depInitiative.Name -Force -ErrorAction SilentlyContinue                    
                }
            }        
        }
    }

    [MessageData[]] RemoveARMPolicies()
    {    
        [MessageData[]] $messages = @();
        if(($this.ARMPolicyObj.Policies | Measure-Object).Count -ne 0)
        {
            if($this.GetApplicableARMPolicies() -ne 0)
            {
                $startMessage = [MessageData]::new("Processing ARM policies. Tags:[$([string]::Join(",", $this.FilterTags))]. Total policies: $($this.GetApplicableARMPolicies().Count)");
                $messages += $startMessage;
                $this.PublishCustomMessage($startMessage);
                $this.PublishCustomMessage("Note: Removing ARM policies can take few minutes depending on number of policies to be processed...", [MessageType]::Warning);                

                $disabledPolicies = $this.GetApplicableARMPolicies() | Where-Object { -not $_.Enabled };
                if(($disabledPolicies | Measure-Object).Count -ne 0)
                {
                    $disabledMessage = "Found ARM policies which are disabled and will not be removed. Total disabled policies: $($disabledPolicies.Count)";
                    $messages += [MessageData]::new($disabledMessage, $disabledPolicies);
                    $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
                }

                $currentPolicies = @();
                $currentPolicies += Get-AzPolicyAssignment | Select-Object -Property Name | Select-Object -ExpandProperty Name
    
                $enabledPolicies = @();
                if($currentPolicies.Count -ne 0)
                {
                    $enabledPolicies += $this.GetApplicableARMPolicies() | Where-Object { $_.Enabled -and $currentPolicies -contains $_.policyDefinitionName };
                }
                
                if($enabledPolicies.Count -ne 0)
                {
                    $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nRemoving following ARM policies from the subscription. Total policies: $($enabledPolicies.Count)", $enabledPolicies);                                            

                    $errorCount = 0;
                    $currentCount = 0;
                    $enabledPolicies | ForEach-Object {
                        $policyName = $_.PolicyDefinitionName;
                        $currentCount += 1;
                        # Remove ARM policy
                        try
                        {
                            Remove-AzPolicyAssignment -Name $_.PolicyDefinitionName -Scope $_.Scope -ErrorAction Stop | Out-Null
                            Start-Sleep -Seconds 15
                            Remove-AzPolicyDefinition -Name $_.PolicyDefinitionName -Force -ErrorAction Stop | Out-Null           
                        }
                        catch
                        {
                            $messages += [MessageData]::new("Error while removing ARM policy [$policyName] from the subscription", $_, [MessageType]::Error);
                            $errorCount += 1;
                        }

                        $this.CommandProgress($enabledPolicies.Count, $currentCount, 2);
                    };

                    [MessageData[]] $resultMessages = @();
                    if($errorCount -eq 0)
                    {
                        #removing the version tag at AzSKRG
                        $azskRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
                        [Helpers]::SetResourceGroupTags($azskRGName,@{[Constants]::ARMPolicyConfigVersionTagName=$this.ARMPolicyObj.Version}, $true)
                        
                        $resultMessages += [MessageData]::new("All ARM policies have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                    }
                    elseif($errorCount -eq $enabledPolicies.Count)
                    {
                        $resultMessages += [MessageData]::new("No ARM policies have been removed from the subscription due to error occurred. Please remove the ARM policies manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error);
                    }
                    else
                    {
                        $resultMessages += [MessageData]::new("$errorCount/$($enabledPolicies.Count) ARM policy(ies) have not been removed from the subscription. Please remove the ARM policies manually or contact AzSK support team.", [MessageType]::Error);
                        $resultMessages += [MessageData]::new("$($enabledPolicies.Count - $errorCount)/$($enabledPolicies.Count) ARM policy(ies) have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                    }
                    $messages += $resultMessages;
                    $this.PublishCustomMessage($resultMessages);
                }
                else
                {
                    $noPolicyMessage = [MessageData]::new("No ARM policies have been configured by AzSK on the subscription. No ARM policies have been removed. ", [MessageType]::Warning);
                    $messages += $noPolicyMessage;
                    $this.PublishCustomMessage($noPolicyMessage);
                    $azskRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
                    [Helpers]::SetResourceGroupTags($azskRGName,@{[Constants]::ARMPolicyConfigVersionTagName=$this.ARMPolicyObj.Version}, $true)
                }
            }
            else
            {
                $this.PublishCustomMessage("No ARM policies have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning);
            }
        }
        else
        {
            $this.PublishCustomMessage("No ARM policies found in the ARM policy file", [MessageType]::Warning);
        }
        return $messages;
    }    

    [void] RemoveARMPolicies([string] $PolicyPrefix, [string] $scope)
    {    
        [MessageData[]] $messages = @();

        $policies = Get-AzPolicyDefinition
        if(($policies | Measure-Object).Count -le 0)
        {
            #return if no policies are found
            return;
        }

        $filteredPolicies = $policies | Where-Object { $_.Name -like "$PolicyPrefix*" }
        if(($filteredPolicies |Measure-Object).Count -le 0)
        {
            #return if no policies are found matching the prefix
            return;
        }

        $policyAssignments = Get-AzPolicyAssignment -Scope $scope

        $filteredPolicies | ForEach-Object {
            try{
                $policy = $_;
                $subPolicyAssignments = @();
                $subPolicyAssignments += $policyAssignments | Where-Object { $_.properties.policyDefinitionId -eq $policy.PolicyDefinitionId }
                if(($subPolicyAssignments | Measure-Object).Count -gt 0)
                {
                    $subPolicyAssignments | ForEach-Object {
                        Remove-AzPolicyAssignment -Name $_.Name -Scope $_.properties.scope -ErrorAction Stop | Out-Null
                    }
                }                        
            }
            catch
            {
                $this.PublishException($_);
            }
        }

        Start-Sleep -Seconds 15
        $filteredPolicies | ForEach-Object {
            try{
                $policy = $_;
                Remove-AzPolicyDefinition -Id $policy.PolicyDefinitionId -Force -ErrorAction Stop | Out-Null
            }
            catch
            {
                $this.PublishException($_);
            }
        }
    }        

    [MessageData[]] SetPolicyInitiative()
    {    
        [MessageData[]] $messages = @();
        #$isPolicyInitiativeEnabled = [ConfigurationManager]::GetAzSKConfigData().EnableAzurePolicyBasedScan;
        $isPolicyInitiativeEnabled = [FeatureFlightingManager]::GetFeatureStatus("EnableAzurePolicyBasedScan",$($this.SubscriptionContext.SubscriptionId))
        try{
            if($isPolicyInitiativeEnabled)
        {
            $initiativeName = [ConfigurationManager]::GetAzSKConfigData().AzSKInitiativeName
            if($null -ne $this.SubPolicyInitiative)
            {
                $this.RemoveDeprecatedInitiatives();
                if($this.SubPolicyInitiative.Name -eq $initiativeName -and ($this.SubPolicyInitiative.Policies | Measure-Object).Count -gt 0)
                {        
                    $initiative = $null;
                    $initiativeAssignment = $null
                    try
                    {            
                        #check if initiative already exists
                        $initiative = Get-AzPolicySetDefinition -Name $initiativeName -ErrorAction SilentlyContinue;
                        if(($initiative|Measure-Object).Count -gt 0)
                        {
                            $initiativeAssignment = Get-AzPolicyAssignment -PolicyDefinitionId $initiative.PolicySetDefinitionId
                        }
                    }
                    catch
                    {
                        #eat this exception as error action is not working
                    }
                    $assignmentName = $initiativeName + "-assignment"
                    $assignmentDisplayName = $this.SubPolicyInitiative.DisplayName + " assignment"
                    $scope = "/subscriptions/$($this.SubscriptionContext.SubscriptionId)"
                    if($null -eq $initiative)
                    {
                        $this.PublishCustomMessage("Creating new AzSK Initiative...", [MessageType]::Update);        
                        $PolicyDefnitions = $this.SubPolicyInitiative.Policies | ConvertTo-Json -depth 10 | Out-String
                        New-AzPolicySetDefinition -Name $initiativeName -DisplayName $this.SubPolicyInitiative.DisplayName -Description $this.SubPolicyInitiative.Description -PolicyDefinition $PolicyDefnitions | Out-Null
                        Start-Sleep -Seconds 15
                        
                    }
                    elseif($this.UpdateInitiative) {
                        $this.PublishCustomMessage("Updating AzSK Initiative...", [MessageType]::Update);
                        $PolicyDefnitions = $this.SubPolicyInitiative.Policies | ConvertTo-Json -depth 10 | Out-String
                        Set-AzPolicySetDefinition -Name $this.SubPolicyInitiative.Name -DisplayName $this.SubPolicyInitiative.DisplayName -Description $this.SubPolicyInitiative.Description -PolicyDefinition $PolicyDefnitions | Out-Null
                        Start-Sleep -Seconds 15                        
                    }
                    elseif($null -ne $initiative)
                    {
                        $this.PublishCustomMessage("Found existing AzSK Initiative.", [MessageType]::Update);    
                    }    
                    if($null -eq $initiativeAssignment)
                    {
                        $setDefnObj = Get-AzPolicySetDefinition -Name $initiativeName -ErrorAction SilentlyContinue;
                        New-AzPolicyAssignment -Name $assignmentName -DisplayName $assignmentDisplayName -Scope $scope -PolicySetDefinition $setDefnObj 
                    }
                    #todo: CA permission update if default CA
                }                
            }
        }
    
        }
        catch
        {
            #eat up exception to allow this functionality to run in preview mode and not to hamper existing functionality
        }
        return $messages;
        
    }

    [string[]] ValidatePolicyConfiguration()
    {        
        $NonCompliantObjects = @();
        $enabledPolicies = $this.GetApplicableARMPolicies() | Where-Object { $_.Enabled };
        if($null -ne $this.ARMPolicyObj -and ($enabledPolicies | Measure-Object).Count -gt 0)
        {
            $RequiredPolicyDefns = @();            
            $enabledPolicies | ForEach-Object {
                $Policy = $_;
                try
                {
                    $PolicyDefn = Get-AzPolicyDefinition -Name $Policy.policyDefinitionName -ErrorAction SilentlyContinue
                    if($null -ne $PolicyDefn)
                    {
                        $RequiredPolicyDefns += $PolicyDefn;
                    }
                }
                catch
                {
                    $NonCompliantObjects += ("Policy :[" + $Policy.policyDefinitionName + "]");
                    #eat this exception as silently continue is not working for this scenario
                }                
            }
            if(($RequiredPolicyDefns | Measure-Object).Count -gt 0)
            {
                $RequiredPolicyDefns | ForEach-Object {
                    $defn = $_;
                    $tassignment = Get-AzPolicyAssignment -PolicyDefinitionId $defn.policyDefinitionId  -ErrorAction SilentlyContinue
                    if($null -eq $tassignment)
                    {
                        $NonCompliantObjects += ("Policy :[" + $defn.Name + "]");
                    }
                }                                                                        
            }    
        }

        $isPolicyInitiativeEnabled = [FeatureFlightingManager]::GetFeatureStatus("EnableAzurePolicyBasedScan",$($this.SubscriptionContext.SubscriptionId))
        if($isPolicyInitiativeEnabled)
        {
            $initiativeName = [ConfigurationManager]::GetAzSKConfigData().AzSKInitiativeName        
            if($null -ne $this.SubPolicyInitiative)
            {                
                if($this.SubPolicyInitiative.Name -eq $initiativeName -and ($this.SubPolicyInitiative.Policies | Measure-Object).Count -gt 0)
                {        
                    $initiative = $null;
                    try
                    {            
                        $initiative = Get-AzPolicySetDefinition -Name $initiativeName -ErrorAction SilentlyContinue;
                    }
                    catch
                    {
                        $NonCompliantObjects += ("Policy Initiative :[" + $initiativeName + "]");
                        #eat this exception as error action is not working
                    }
                    if($null -ne $initiative)
                    {
                        $policyDefinitions = $initiative.Properties.policyDefinitions;
                        $this.SubPolicyInitiative.Policies | ForEach-Object {
                            $configuredPolicyDefn = $_;
                            if(($policyDefinitions | Where-Object { $_.policyDefinitionId -eq $configuredPolicyDefn.policyDefinitionId} | Measure-Object).Count -le 0)
                            {
                                $NonCompliantObjects += ("Policy Initiative :[" + $initiativeName + "] -> Definition :[" + $_.policyDefinitionId + "]");
                            }
                        }
                    }                
                }
            }
        }
        return ($NonCompliantObjects | Select-Object -Unique);
    }
}

class ARMPolicyModel
{
    [string] $Version
    [PSObject[]] $Policies
    [string[]] $DeprecatedPolicies
}

class PolicyInitiative 
{
    [string] $Version;
    [string] $Name;
    [string] $DisplayName;
    [string] $Description;
    [PSObject[]] $Policies;    
    [string[]] $DeprecatedInitiatives;
}