GuestConfigurationTroubleshooter.psm1

<#
.SYNOPSIS

Gets the properties of the GuestConfig Extension on a specified VM
    
.DESCRIPTION

This script gets and prints the properties of the GuestConfig Extension on a specified windows
or linux vm.

.PARAMETER ResourceGroupName
The Resource Group the VM is in

.PARAMETER VMName
The VM to get the GuestConfig Extension from

.EXAMPLE

PS> Get-VmGuestConfigExtensionProperties -ResourceGroupName "MyResourceGroup" -VMName "MyVM"
Checking AzurePolicyforWindows...
The extension AzurePolicyforWindows was deployed successfully
Provisioning succeeded
#>

function Get-VmGuestConfigExtensionProperties
{
    [CmdletBinding()]
    param(
        [parameter(Mandatory=$true)][String]$ResourceGroupName,
        [parameter(Mandatory=$true)][String]$VMName
    )

    #Get the VM to check whether it is linux or windows
    $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -ErrorAction SilentlyContinue

    if(-not($vm))
    {
        throw "The given VM could not be found in that Resource Group"
    }

    #If it is a windows machine
    if($vm.OSProfile.WindowsConfiguration)
    {
        #Get the extension
        $ext = Get-AzVMExtension -ResourceGroupName $ResourceGroupName -VMName $VMName -Name "AzurePolicyforWindows" -ErrorAction SilentlyContinue

    }
    #Otherwise if it is a linux machine
    elseif($vm.OSProfile.LinuxConfiguration)
    {
        #Get the extension
        $ext = Get-AzVMExtension -ResourceGroupName $ResourceGroupName -VMName $VMName -Name "AzurePolicyforLinux" -ErrorAction SilentlyContinue
    }
    else
    {
        Write-Warning "That VM's OS is not supported by Guest Configuration"
        return $false
    }

    Write-Host ("Checking for extension `"" + $ext.Name + "`"...")

    #If the extension is deployed
    if($ext)
    {
        Write-Host ("The extension `"" + $ext.Name + "`" was deployed successfully")

        #Check the provisioning state
        if($ext.ProvisioningState -eq "Succeeded")
        {
            Write-Host "Provisioning succeeded"
        }
        else
        {
            $warningString = "Provisioning did not succeed, provisioning state is: " + $ext.ProvisioningState
            Write-Warning $warningString

            if($ext.ProvisioningState -eq "Not Started" -or $ext.ProvisioningState -eq "In Progress" -or $ext.ProvisioningState -eq "Updating")
            {
                Write-Warning "Deployment for this extension is still in progress, wait for a couple minutes"
            }
            elseif($ext.ProvisioningState -eq "Failed")
            {
                Write-Warning "Provisioning for this extension has failed, try running a remediation task"
            }

            return $false
        }


    }
    else
    {
        $warningString = "The extension `"" + $ext.Name + "was not deployed successfully or was not deployed at all"
        Write-Warning $warningString
        Write-Warning "Check if any DeployIfNotExists Policies are assigned to this scope"
        return $false
    }

    return $true

}

<#
.SYNOPSIS

Gets the MSI Status of a VM
    
.DESCRIPTION

This script gets and prints the MSI Status of a specified VM in a specified Resource Group

.PARAMETER ResourceGroupName
The Resource Group the VM is in

.PARAMETER VMName
The VM to check the MSI status of

.EXAMPLE

PS> Get-VmMSIEnabled -ResourceGroupName "MyResourceGroup" -VMName "MyVM"
MSI is enabled on this VM
#>

function Get-VmMSIEnabled
{
    [CmdletBinding()]
    param(
        [parameter(Mandatory=$true)][String]$ResourceGroupName,
        [parameter(Mandatory=$true)][String]$VMName
    )

    #Get the VM to check MSI status
    $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -ErrorAction SilentlyContinue

    #Check if the VM was found
    if(-not($vm))
    {
        throw "The given VM could not be found in that Resource Group"
    }

    if($vm.Identity.Type -eq "SystemAssigned")
    {
        Write-Host "MSI is enabled on this VM"
        return $true
    }
    else
    {
        Write-Warning "MSI is not enabled on this VM"
        Write-Warning "Enabling System Managed Identity is needed for Guest Configuration Policy scenarios"
        return $false
    }


}


<#
.SYNOPSIS

Prints warnings and errors for any Guest Configuration policies that were assigned incorrectly
    
.DESCRIPTION

This script checks all Guest Configuration policies in a given resource group
and prints warnings and errors if any of them were assigned incorrectly

.PARAMETER ResourceGroupName
The Resource Group to check policies in

.PARAMETER Subscription
Switch parameter that allows you to check the policy assignments in the current subscription
(Context based)

.EXAMPLE

PS> Get-GuestConfigPolicyErrors -ResourceGroupName "MyResourceGroup"

.EXAMPLE

PS> Get-GuestConfigPolicyErrors -Subscription
#>

function Get-GuestConfigPolicyErrors
{
    [CmdletBinding()]
    param(
        [parameter(ParameterSetName = "ResourceGroup", Mandatory=$true)][String]$ResourceGroupName,
        [parameter(ParameterSetName = "Subscription", Mandatory=$true)][Switch]$CurrentSubscription
    )

    if(-not($CurrentSubscription))
    {
        $rg = Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue

        if(-not($rg))
        {
            throw "The given Resource Group could not be found"
        }

        #Get all policies in the resource group
        $assignments = Get-AzPolicyAssignment -Scope $rg.ResourceId
    }
    else
    {
        $assignments = Get-AzPolicyAssignment
    }

    #for tracking status
    $success = $true
    $totalErrors = 0
    $guestConfigCount = 0

    #If there are any policies
    if($assignments.Count -gt 0)
    {
        
        #Loop through each policy
        foreach($assignment in $assignments)
        {
            #Get the policies definition
            $id = $assignment.Properties.policyDefinitionId

            $verboseMessage = "Checking policy assignment `"" + $assignment.Properties.displayName + "`""

            Write-Verbose $verboseMessage

            #Check if there is an id
            if($id)
            {
                
                $def = Get-AzPolicyDefinition -Id $id

                #Check if it is a Guest Configuration Policy
                if($def.Properties.metadata.category -eq "Guest Configuration")
                {

                    Write-Verbose "Found Guest Configuration policy"
                    $guestConfigCount += 1

                    #Check if the policy is in an initiative
                    if($def.Properties.policyDefinitions)
                    {
                        Write-Verbose "Policy was in an initiative"
                    }
                    else
                    {
                        #If it's not in an initiative, print information
                        $warningString = "The policy `"" + $def.Properties.displayName + "`" is not in an initiative"
                        Write-Warning $warningString
                        
                        $success = $false

                        $totalErrors += 1

                        if($def.Properties.policyRule.then.effect -eq "deployIfNotExists")
                        {
                            Write-Warning "It is recommended that the DeployIfNotExists Policy be in an initiative with its corresponding Audit Policy"
                            Write-Warning "The corresponding Audit Policy is missing" 
                        }
                        elseif($def.Properties.policyRule.then.effect -eq "audit")
                        {
                             
                            Write-Warning "It is recommended that the Audit Policy be in an initiative with its corresponding DeployIfNotExists Policy"
                            Write-Warning "The corresponding DeployIfNotExists Policy is missing"
                        }

                        #to separate policies
                        Write-Host ""
                    }
                }
            }
        }
    }

    #Write information about the total amount of errors
    if($guestConfigCount -eq 0)
    {
        Write-Host "There are no Guest Configuration Policies assigned to this scope"
    }
    elseif($totalErrors -gt 0)
    {
        Write-Host "Total Guest Config Policy errors:" $totalErrors -ForegroundColor Red
    }
    else
    {
        Write-Host "Total Guest Config Policy errors:" $totalErrors -ForegroundColor Green
    }

    return $success

}

<#
.SYNOPSIS

Tests VM/ResourceGroup/Subscription for things related to Guest Configuration
    
.DESCRIPTION

This script runs the cmdlets: Get-VmGuestConfigExtensionProperties, Get-VmMSIEnabled, Get-GuestConfigPolicyErrors
and prints status information based on results

.PARAMETER ResourceGroupName
The Resource Group to run tests in

.PARAMETER VMName
The VM to run tests on

.PARAMETER CheckSubscriptionPolicies
Switch parameter that allows you to check policy assignments on a subscription level
(based on current context)

.EXAMPLE

PS> Test-GuestConfigurationPolicies -ResourceGroupName "MyResourceGroup" -VMName "MyVM"

.EXAMPLE

PS> Test-GuestConfigurationPolicies -ResourceGroupName "MyResourceGroup" -VMName "MyVM" -CheckSubscriptionPolicies
#>

function Test-GuestConfigurationPolicies
{
    [CmdletBinding()]
    param(
        [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][String]$ResourceGroupName,
        [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][String]$VMName,
        [parameter(Mandatory=$false)][switch]$CheckSubscriptionPolicies
    )

    #Check if the resource group exists (MSIEnabled and ExtensionProperties will check the VM)
    if(-not(Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue))
    {
        throw "The given Resource Group could not be found"
    }


    Write-Host ""
    
    #Check MSI on the given VM
    Write-Host "Checking if MSI is enabled on this VM"
    $status1 = Get-VmMSIEnabled -ResourceGroupName $ResourceGroupName -VMName $VMName
    if($status1 -eq $true)
    {
        Write-Host "MSI Enabled status: Success" -ForegroundColor Green
    }
    else
    {
        Write-Host "MSI Enabled status: Failed" -ForegroundColor Red
    }
    Write-Host ""


    #Check Guest Config Extension on the given VM
    Write-Host "Checking properties of Guest Configuration Extension on this VM"
    $status2 = Get-VmGuestConfigExtensionProperties -ResourceGroupName $ResourceGroupName -VMName $VMName
    if($status2 -eq $true)
    {
        Write-Host "Guest Config Extension Status: Success" -ForegroundColor Green
    }
    else
    {
        Write-Host "Guest Config Extension Status: Failed" -ForegroundColor Red
    }
    Write-Host ""


    #Check assignment errors
    Write-Host "Checking if all Guest Config policies were assigned correctly in specified scope"
    if(-not($CheckSubscriptionPolicies))
    {
        $status3 = Get-GuestConfigPolicyErrors -ResourceGroupName $ResourceGroupName
    }
    else
    {
        $status3 = Get-GuestConfigPolicyErrors -CurrentSubscription
    }

    if($status3 -eq $true)
    {
        Write-Host "Guest Config Policy Assignments: Success" -ForegroundColor Green
    }
    else
    {
        Write-Host "Guest Config Policy Assignments: Failed" -ForegroundColor Red
    }
    Write-Host ""

    #Overall status is only success if all 3 checks succeeded
    if($status1 -and $status2 -and $status3)
    {
        Write-Host "Overall status: Success" -ForegroundColor Green
    }
    else
    {
        #Print Verbose information
        if(-not($status1))
        {
            Write-Verbose "MSI: Failed"
        }
        if(-not($status2))
        {
            Write-Verbose "Guest Config Extension: Failed"
        }
        if(-not($status3))
        {
            Write-Verbose "Guest Config Policy Assignments: Failed"
        }
        Write-Host "Overall status: Failed" -ForegroundColor Red
    }
}

Export-ModuleMember -Function Get-VmGuestConfigExtensionProperties, Get-VmMSIEnabled, Get-GuestConfigPolicyErrors, Test-GuestConfigurationPolicies