How to use Update-MgDeviceManagementDeviceCompliancePolicy - Cannot apply PATCH to navigation property 'scheduledActionsForRule'

Tor André Solbakken 40 Reputation points
2024-11-28T12:04:06.47+00:00

Hi all,

I am trying to programatically update the "Actions for noncompliance" when a compliance policy already exist.

This is the function with parameters I am passing, it works for the first-time creation of the policy. (It originally included Win11 also, but that creation part is left out for now)


function Create-DeviceCompliancePolicies2 {
    <#
    .DESCRIPTION
    This function configures the Device Specific Compliance Policies for Windows 10 and 11 Devices.
    #>

    <#
    .NOTES
    The grace period is defined in hours when done programmatically, unlike in the GUI where it is in days.
    #>

    # Define variables for shared values
    $MinimumOSVersionW10 = "10.0.19045.5011"
    $MinimumOSVersionW11 = "10.0.22631.4317"
    $DeviceGracePeriodInHours = 336

    # Define the compliance policy parameters for Windows 10
    $params1 = @{
        "@odata.type" = "#microsoft.graph.windows10CompliancePolicy"
        description = "Default Compliance policy for all Windows 10 devices"
        displayName = "Windows 10 - Default Compliance Policy"
        version = 7
        passwordRequired = $false
        passwordBlockSimple = $false
        passwordExpirationDays = $null
        passwordMinimumLength = $null
        passwordMinutesOfInactivityBeforeLock = $null
        passwordMinimumCharacterSetCount = $null
        passwordRequiredType = "deviceDefault"
        passwordPreviousPasswordBlockCount = $null
        osMinimumVersion = $MinimumOSVersionW10
        osMaximumVersion = $null
        earlyLaunchAntiMalwareDriverEnabled = $false
        bitLockerEnabled = $true
        secureBootEnabled = $true
        codeIntegrityEnabled = $false
        activeFirewallRequired = $true
        defenderEnabled = $true
        antivirusRequired = $true
        antiSpywareRequired = $true
        deviceThreatProtectionEnabled = $true
        deviceThreatProtectionRequiredSecurityLevel = "medium"
        tpmRequired = $true
        scheduledActionsForRule = @(
            @{
                "@odata.type" = "#microsoft.graph.deviceComplianceScheduledActionForRule"
                ruleName = "PasswordRequired"
                scheduledActionConfigurations = @(
                    @{
                        "@odata.type" = "#microsoft.graph.deviceComplianceActionItem"
                        actionType = "block"
                        gracePeriodHours = $DeviceGracePeriodInHours
                        notificationTemplateId = $null
                        notificationMessageCcList = @()
                    }
                )
            }
        )
    }

    # Process Windows 10 Policy
    $policyNameW10 = "Windows 10 - Default Compliance Policy"
    Write-Host "Checking for existing policy with the name '$policyNameW10'..."
    $existingPolicyW10 = Get-MgDeviceManagementDeviceCompliancePolicy -Filter "displayName eq '$policyNameW10'"

    if ($existingPolicyW10) {
        Write-Host "Policy '$policyNameW10' found. Updating the existing policy..."
        Update-MgBetaDeviceManagementDeviceCompliancePolicy -DeviceCompliancePolicyId $existingPolicyW10.Id -BodyParameter $params1 #-ErrorAction SilentlyContinue
        Write-Host "Policy '$policyNameW10' updated successfully."
    } else {
        Write-Host "Policy '$policyNameW10' not found. Creating a new policy..."
        New-MgBetaDeviceManagementDeviceCompliancePolicy -BodyParameter $params1 -ErrorAction SilentlyContinue
        Write-Host "Policy '$policyNameW10' created successfully."
    }
}


Subsequent runs will throw an error.

Update-MgBetaDeviceManagementDeviceCompliancePolicy : Cannot apply PATCH to navigation property
'scheduledActionsForRule' on entity type 'microsoft.management.services.api.deviceCompliancePolicy'.
Status: 400 (BadRequest)
ErrorCode: ModelValidationFailure
Date: 2024-11-28T11:49:16
Headers:
Transfer-Encoding             : chunked
Vary                          : Accept-Encoding
Strict-Transport-Security     : max-age=31536000
request-id                    : b8acb9ca-bd26-403f-b157-9277f7eb51d5
client-request-id             : 466ac257-5267-437f-b763-65400e41a218
x-ms-ags-diagnostic           : {"ServerInfo":{"DataCenter":"Norway
East","Slice":"E","Ring":"2","ScaleUnit":"000","RoleInstance":"OSL0EPF0000051D"}}
Date                          : Thu, 28 Nov 2024 11:49:16 GMT
At line:68 char:9
+         Update-MgBetaDeviceManagementDeviceCompliancePolicy -DeviceCo ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ({ DeviceComplia...pliancePolicy }:<>f__AnonymousType255`3) [Update-Mg
   BetaDe...cePolicy_Update], Exception
    + FullyQualifiedErrorId : ModelValidationFailure,Microsoft.Graph.Beta.PowerShell.Cmdlets.UpdateMgBetaDeviceManagem
   entDeviceCompliancePolicy_Update

I can work around it with deleting the policy and recreate it, but then the devices starts the grace period all over, so it's not a solution.

Any good suggestions on how I can update the policy with just the scheduledActionsForRule part?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,512 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.