Windows Autopatch: Auto-remediation with PowerShell scripts

  • Thread starter Thread starter Ken_Goossens
  • Start date Start date
K

Ken_Goossens

Windows Autopatch deploys and continuously monitors Microsoft Intune policies to enrolled tenants. Policy conflicts can occur when there are two or more policies in the tenant and might impact Windows updates in Windows Autopatch. Let's take a look at what causes policy conflicts and, more importantly, how you can easily resolve them with PowerShell scripts.



Important: This solution is for you if you currently use Microsoft Intune and don't use third-party application patching solutions with Microsoft Configuration Manager.

The origin of Windows update policy conflicts


Policy conflicts can prevent successful deployment of Windows quality and feature updates. These issues are common in environments that rely on Configuration Manager and Group Policy Objects (GPOs).

Have you transitioned to modern management through co-management and shifted the control slider to Microsoft Intune? This step is crucial for enabling Windows Autopatch. However, legacy configurations can leave registry artifacts that disrupt the service operations.

When you use Configuration Manager, it's important you don't enable software update client settings that might conflict with Autopatch policies. If you currently allow or plan to allow Microsoft 365 app updates for Windows Autopatch–enrolled devices, the best practice is to disable Office updates via Configuration Manager. Alternatively, if you don't use Configuration Manager to distribute third-party application updates, you can disable the software update client entirely. Please make sure that you remove any existing client configuration that can conflict with Autopatch, unless you're using a third-party application patching solution. Review how in Client settings in Configuration Manager.

However, even well-configured environments might retain registry artifacts in the registry. Take these primary actions, for which we provide details below, to address update-policy-related registry artifacts:


Note: This solution is based on recommendations in our official documentation, such as Conflicting configurations.

Copy the detection script


This PowerShell script performs several operations to detect and log specific Windows Update policy settings that could prevent correct update deployments. The detection script:

  1. Defines log location and name. The script sets up variables for the path ($TranscriptPath) and name ($TranscriptName) of the log file where it will store the output. These point to a log file named "AutoPatchDetection.log" within the following folder: C:\ProgramData\Microsoft\IntuneManagementExtension\Logs.
  2. Creates log directory (if necessary). The script attempts to create the directory specified by $TranscriptPath if it doesn't already exist, using the -Force parameter to overwrite any existing files without prompting for confirmation.
  3. Stops orphaned transcripts. The script checks for any leftover PowerShell logging sessions and stops them to prevent interference. If there's no active transcript session, it catches the resulting error and does nothing, preventing the script from stopping.
  4. Starts transcription. The script begins a new transcription session. It saves the output to the specified log file and appends to it if it already exists.
  5. Creates registry key array. The script creates an array ($regkeys) to hold objects representing specific registry keys related to Windows Update policies. Each object contains a name and a path indicating the location of the registry key and the value that it's looking for.
  6. Populates array with key information. The script adds objects to the $regkeys array representing the following registry keys:
    • DoNotConnectToWindowsUpdateInternetLocations
    • DisableWindowsUpdateAccess
    • NoAutoUpdate


    Important: These keys are associated with policies that might limit the functionality of Windows updates.
  7. Checks registry settings. The script iterates over each object in the $regkeys array, checking if the specified registry key exists and contains the specified property (expected policy setting). If it finds a key that matches, the script raises a flag $RemediationNeeded. This flag indicates that there are registry settings that need correction and have been logged.
  8. Logs and exits based on findings.
    • If any incorrect settings were detected ($RemediationNeeded -eq $true), the script logs the issue, ends the logging session, and exits with code 1. Code 1 indicates that an error was found.
    • If no problems are found, the script logs that the registry settings are correct, stops logging, and exits with code 0. Code 0 indicates that everything is in order.

Tip: You can either copy the code presented here, or, if you want to engage with your peers, get it from GitHub.





Code:
$TranscriptPath = "C:\ProgramData\Microsoft\IntuneManagementExtension\Logs"
$TranscriptName = "AutoPatchDetection.log"
new-item $TranscriptPath -ItemType Directory -Force

# stopping orphaned transcripts
try
{
    stop-transcript|out-null
}
  catch [System.InvalidOperationException]
{}

Start-Transcript -Path $TranscriptPath\$TranscriptName -Append

# initialize the array
[PsObject[]]$regkeys = @()
# populate the array with each object
$regkeys += [PsObject]@{ Name = "DoNotConnectToWindowsUpdateInternetLocations"; path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\"}
$regkeys += [PsObject]@{ Name = "DisableWindowsUpdateAccess"; path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\"}
$regkeys += [PsObject]@{ Name = "NoAutoUpdate"; path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU\"}

foreach ($setting in $regkeys)
{
    write-host "checking $($setting.name)"
    if((Get-Item $setting.path -ErrorAction Ignore).Property  -contains $setting.name)
    {
        write-host "$($setting.name) is not correct"
        $RemediationNeeded = $true
    }
}

if ($RemediationNeeded -eq $true)
{
    write-host "registry settings are incorrect"
    Stop-Transcript
    exit 1
}
else 
{
    write-host "registry settings are correct"
    Stop-Transcript
    exit 0
}





Copy the remediation script


You can remediate Windows Update policy conflicts with this PowerShell script. It removes specific registry keys that can prevent updates from being deployed successfully. The remediation script:

  1. Sets up log file. It establishes a file name and a directory where the script's output will be recorded for logging purposes: C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\AutoPatchRemediation.log.
  2. Creates log directory (if necessary). The script ensures the existence of the specified directory for the log file. If it doesn't already exist, the script creates it using the -Force parameter to override any potential issues without prompting.
  3. Stops orphaned transcripts. It attempts to stop any transcription (logging) sessions that might have been left running previously. If no such session is active, and an error occurs, it catches the error to prevent the script from failing at this point.
  4. Starts new transcription. It begins logging the script's output to the specified log file, appending to it if the file already exists. This process records all actions taken by the script.
  5. Creates registry key array. It creates an array to hold objects, each representing a specific registry key related to Windows Update policies that might cause conflicts.
  6. Populates array with target keys. The script adds several objects to this array, each specifying the name and path of a registry key that potentially conflicts with Windows updates. These keys include:
    • DoNotConnectToWindowsUpdateInternetLocations
    • DisableWindowsUpdateAccess
    • NoAutoUpdate
  7. Remediates conflicts. For each registry key object in the array, the script checks if the specified key exists and contains the property (name) indicated.
    • If the property exists and indicates a potential policy conflict, the script removes this property from the registry to remediate the conflict. It then logs this action.
    • If the property does not exist, it logs that the specific setting was not found. In that case, no action is needed for that key.
  8. Stops transcription. Once all specified registry keys have been checked and remediated as necessary, the script stops logging its actions and closes the log file.

Tip: You can either copy the code presented here, or, if you want to engage with your peers, get it from GitHub.





Code:
$TranscriptPath = "C:\ProgramData\Microsoft\IntuneManagementExtension\Logs"
$TranscriptName = "AutoPatchRemediation.log"
new-item $TranscriptPath -ItemType Directory -Force

# stopping orphaned transcripts
try
{
    stop-transcript|out-null
}
  catch [System.InvalidOperationException]
{}

Start-Transcript -Path $TranscriptPath\$TranscriptName -Append

# initialize the array
[PsObject[]]$regkeys = @()
# populate the array with each object
$regkeys += [PsObject]@{ Name = "DoNotConnectToWindowsUpdateInternetLocations"; path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\"}
$regkeys += [PsObject]@{ Name = "DisableWindowsUpdateAccess"; path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\"}
$regkeys += [PsObject]@{ Name = "NoAutoUpdate"; path = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU\"}

foreach ($setting in $regkeys)
{
    write-host "checking $($setting.name)"
    if((Get-Item $setting.path -ErrorAction Ignore).Property -contains $setting.name)
    {
        write-host "remediating $($setting.name)"
        Remove-ItemProperty -Path $setting.path -Name $($setting.name)
    }
    else
    {
        write-host "$($setting.name) was not found"
    }
}

Stop-Transcript





Upload and deploy the scripts in Microsoft Intune


So, let's execute our developed solution. First, we'll deploy the detection and remediation scripts through Microsoft Intune. Here's where you can ensure precise configuration adjustments, resolve policy conflicts, and enhance Windows update deployments with Windows Autopatch.

Creating a new remediation script

  1. Sign in to https://intune.microsoft.com.
  2. Navigate to Devices.
  3. Select Scripts and remediations. Out of the available script options, select Remediations.
  4. Select Create to start creating a new custom script.

    Screenshot of the Devices page in Microsoft Intune admin center, focused on Scripts and remediations options.Screenshot of the Devices page in Microsoft Intune admin center, focused on Scripts and remediations options.
  5. To Create custom script, you'll complete all required information step by step in the wizard as shown below.

Using the wizard to create a custom script


Let's walk through the wizard to create a custom script based on our recommendations.

  1. In the Basics tab, give your script a name and fill out the following details:
    • Name: Enter the name of your remediation script. For example, you can call it "Windows Autopatch – Auto-remediation policies."
    • Description (optional): Enter a description with helpful details about this script.
    • Publisher (automatic): Your name is automatically filled in, but you can change it.
    • Version: Give your script a version number. This helps you track changes and ensures consistency across deployments.

      Screenshot of the Basics tab in Create custom script in Microsoft Intune admin center.Screenshot of the Basics tab in Create custom script in Microsoft Intune admin center.
  2. In the Settings tab, add detection and remediation scripts to the solution:
    • Add detection script: Select the folder icon to locate your detection script and open it. This will add the script.
    • Add remediation script: Select the folder icon to locate the remediation script and open it. This will add the script.
  3. Make sure to keep the default settings of "No" on all the following script behaviors. (Tip: Move down the page if you don't see these options right away.)
    • Run this script using the logged-on credentials: No
    • Enforce script signature check: No
    • Run script in 64-bit PowerShell: No

      Screenshot of the Settings tab in Create custom script in Microsoft Intune admin center.Screenshot of the Settings tab in Create custom script in Microsoft Intune admin center.
  4. In the Scope tags tab, select your scope tags if you wish to use them.
  5. In the Assignment tab, configure the deployment options as follows:
    • Assign to: You can ignore this option for now.
    • Assignment group: Select the "Windows Autopatch – Devices All" group. That will ensure that you target all devices registered in the Windows Autopatch service.
    • Schedule: Select Daily to edit the schedule for your remediation. You have multiple options to run the script. You can run it once, hourly, or daily. You can choose if and how often to repeat it. You can also choose a start time. Note: We recommend running this script every hour to remediate any drifts.
    • Filter: Optionally, use filters to assign a policy based on the rules that you created earlier. We're not using filters in this guide.
    • Filter mode: Optionally, include or exclude the groups that receive the filter assignment.

      Screenshot of the Assignments tab in Create custom script in Microsoft Intune admin center.Screenshot of the Assignments tab in Create custom script in Microsoft Intune admin center.
  6. Select Next to review your settings and create your remediation script.
  7. Select Create. If all goes as planned, you'll now have your remediation script created and assigned to all your Windows Autopatch devices.

Monitor script execution


After deployment, use Intune to monitor the execution status and outcomes of your scripts through the Device status page within Proactive remediation script.

Screenshot of the Device status page for the created auto-remediation policies in Microsoft Intune admin center.Screenshot of the Device status page for the created auto-remediation policies in Microsoft Intune admin center.

If you select the script package name in Remediations, you'll get some information about how your script package is performing

If you'd like to have more insights into the Detection status and Remediations status metrics, check the Overview page.

Screenshot of the Overview page with your auto-remediation policies in Microsoft Intune admin center.Screenshot of the Overview page with your auto-remediation policies in Microsoft Intune admin center.

Collect log files


We have some intelligence built into our scripts. It's contained in log files that are being saved in the Microsoft Intune Management Extension (IME) Log folder.



Important: The generated log files are stored in the IME folder C:\ProgramData\Microsoft\IntuneManagementExtension\Logs. This simplifies the diagnostic process and allows for easy collection through Intune.

Use the Collect diagnostics function in Intune to obtain these log files produced by the detection and remediation scripts. Here are the steps to collect and read the logs:

  1. From https://intune.microsoft.com, navigate to Devices.
  2. Go to All devices.
  3. Enter your device name in the search bar.
  4. Select the device name to view the device's information.
  5. Select Collect diagnostics to ask Intune to gather the diagnostic data from the device.

    Screenshot of the Collect diagnostics tab in Microsoft Intune admin center, illustrating how to collect diagnostics for your device.Screenshot of the Collect diagnostics tab in Microsoft Intune admin center, illustrating how to collect diagnostics for your device.
  6. Once the diagnostic files are uploaded, the Device action status changes from "Pending" to "Complete." (Tip: You might want to hit F5 a couple times to speed up the refresh in the console.) If you wish, you can download the zip file with all the log files from the Device diagnostics page for each device.

    Screenshot of the Device diagnostics page in Microsoft Intune admin center, illustrating how to check a device’s status.Screenshot of the Device diagnostics page in Microsoft Intune admin center, illustrating how to check a device’s status.
  7. Open the zip file and search for the IntuneManagementExtension_Logs folder. That folder contains our two log files created by the remediation script. If no remediation was required, you'll have only the detection log.

    Screenshot of a File Explorer window, showing an example of the log files that you will find in your zip file.Screenshot of a File Explorer window, showing an example of the log files that you will find in your zip file.
  8. If you want to know if the remediations were executed, search for "remediating" in the autopatchremediation.log file. You'll notice that every check is listed in the log. Whenever a drift is detected, it will be flagged for remediation by the detection script.

    Screenshot of a remediation log file, highlighting how to check that a remediation was executed.Screenshot of a remediation log file, highlighting how to check that a remediation was executed.

Final considerations


By following these guidelines, you can streamline update deployments and maintain system integrity.



Important: Make sure to test this in your environment on a small set of devices before pushing it out.

In the complex ecosystem of modern IT environments, ensuring the smooth deployment of Windows updates is critical. With these auto-remediation scripts you can resolve policy conflicts and maintain system performance more effectively with Windows Autopatch.



Continue the conversation. Find best practices. Bookmark the Windows Tech Community, then follow us @MSWindowsITPro on X and on LinkedIn. Looking for support? Visit Windows on Microsoft Q&A.

Continue reading...
 
Back
Top