MSEndpointMgr
a picture of fry from futurama looking at intune configurations

Force Intune policy sync from a PowerShell script

Ever wondered how you can kick off a manual or automatic sync of your Intune policies from a PowerShell script?

Not long ago I ran into the need to have policies applied to new devices, a lot quicker than what a normal enrollment does.

Because I had multiple users on shared computers, and a lot of roaming going on, I needed the user enrollment process to be as snappy as possible, but most times it would fail to apply all user policies in the first go, and a reboot might have solved it, but that was unacceptable in this case.

UPDATE: October 21st 2019

Added a separate script to deal with iOS and Android devices in bulk.
This script will get all your iOS and Android devices that are enrolled with Microsoft Intune and signal them to update their MDM policies.

Download Invoke-IntunePolicySyncOniOSAndAndroid.ps1 from GitHub

UPDATE: September 29th 2019

Michael Niehaus (@mniehaus) has answered my prayers for feedback, and boy does he deliver!
In his blog post “Forcing an MDM sync from a Windows 10 client“, Niehaus walks us through his investigation methods, and ends up with a one-liner that solves this whole issue completely (almost).

I will leave the solution below as-is, because it also works from the users context without requiring extra permissions.

The current limitations

So at the moment the only GUI methods that exist to “force” a sync of your policies, is by using the sync button from within the Intune portal,  or from the client – by using the sync button in the Company Portal app or the Work and School account settings page.

manual intune sync
Syncing a device via the Intune portal.

And when I say “force”, I really mean that it will only look for missing or updated policies that haven’t applied – No built-in method exists to have all policies re-evaluate and re-apply.

It is possible to delete the policies and have them reapply by using PowerShell, but that’s not the subject of this article.

The path forward

Keeping in mind that I am working from a pure Intune perspective here (no ConfigMgr available), there was only one course I could see ahead of me, and that was to come up with a PowerShell solution. So this article is really just to tell you it can be done, and I have the Proof-Of-Concept running in production today with good results.

And since it’s not that complex a script, I suggest you read it through from start to end, to really understand what’s going on, as I don’t recommend implementing workarounds like this without fully understanding what it is and does.

Why you might need this workaround

Well as I said, I needed it for a shared PC scenario, but you might also just want to avoid too many reboots during first enrollment, or to further automate your deployment sequence. In any case, I thought I would share it, at least for inspiration and feedback from the community (please use GitHub for code feedback / bugs / updates).

Script overview

So this script essentially does the following:

  • Checks for the Microsoft.Graph.Intune PowerShell Module.
  • Installs / Imports the module.
  • Connects to the Intune Graph.
  • Finds the Device ID based on the hostname of the device you are executing on.
  • Tells Intune to start syncing policies for said device.

Prerequisites

The prerequisites for this to have any chance of working, is that you grant admin consent by running the following bits of PowerShell on your own Windows PC, form an elevated PowerShell prompt.

Install-Module -Name Microsoft.Graph.Intune
Import-Module -Name Microsoft.Graph.Intune
Connect-MSGraph -AdminConsent

If you are unfamiliar with the term “Admin Consent”, I strongly suggest that you read up on it, because this will be come more prevalent in future app´s. Here is a good resource from the creators of all that is holy to us: Admin consent experience

Next thing to do, is download the script and read my suggestions for deployment if you want inspiration. I am sure you will come up with other good ways to use this, so please share those in the comments section for others to read.

Download

Invoke-IntunePolicySync.ps1 on GitHub

Deployment options

Here are a few methods for deploying this, and what I ended up doing in my scenario (spoiler: it’s not very pretty).

  • Deployed as a Device Configuration PowerShell script assigned to the user.
    • This will run only the first time a user logs on, but might not be effective enough if you have many policies etc.
    • Try throwing a DO WHILE loop into the mix that iterates through the script a few times with a few minutes of sleep time in between the iterations.
  • Deployed through GPO as a logon script.
    • This will run every single time a user logs on to the machine, so you might want to place a cookie somewhere on the device to stop it from running all the time.

I ended up with the GPO, since I also had some lingering Group Policies that needed to be forced onto the machine right after a refresh, so I slammed in a “gpupdate /force” and just made the script switch back and forth between the gpupdate and the Intune sync, with a minute of waiting in between.

This works like a charm on newly deployed machines, not only shared computers, and it saves me a reboot or two.
Though for newly deployed machines I just put it in as part of the initial deployment sequence.

But it is ugly as hell, and I might get throttled by Microsoft if I deploy too many machines that try to force a policy sync this often – tho it has yet to be seen.

Try it out and have fun with it.

Don’t forget to subscribe to our RSS feed and follow me on Twitter @michael_mardahl.

Michael Mardahl

Michael Mardahl is a seasoned IT pro with over 25 years of experience under his belt. He's a Microsoft Certified Cloud Architect at APENTO in Denmark, where he helps customers move from traditional infrastructure to the cloud while keeping security top of mind. When he's not working, Michael's either spending time with his family and friends or passionately blogging about Microsoft cloud technology. His expertise in this area has even earned him the prestigious title of Microsoft Most Valuable Professional (MVP) in both the Enterprise Mobility and Security categories. In short, Michael is the IT equivalent of a rockstar, but don't expect him to act like one - he's way too down-to-earth for that.

14 comments

  • Hi Michael,
    We have more than 400 computers on Intune. And every month we find few computers are not syncing to Intune. Even If I click the “Sync” button on Intune portal, cannot communicate with the device; though the device is connected to the internet.
    The only way to fix it, when we ask the user to go to the “company portal” app or click “change account setting” and click the “sync” there.
    Is there any way we can run a powershell script (we can deploy through GPO) that will check if the Sync with Intune is more than 24 hrs then, it will trigger a Sync from the computer manually.
    Please let me know.

    • Hi Rony,

      Yes, you would have to build a script that polls for the last sync time and then fire the scheduled task mentioned in Michael Niehaus blog that I link to in the begning of the article.

      ChatGPT says this should work.
      I think it needs some tinkering ;). So, I will leave that up to you and hope you will post back with a working script 🙂

      # Get the current Intune sync status
      $syncStatus = (Get-CimInstance -Namespace root/ccm/DmRcw -ClassName MSFT_IntuneDeviceManagementConnector).LastSyncStatus

      # Get the current date and time
      $currentDate = Get-Date

      # Check if the last sync was more than 3 days ago
      if ($syncStatus -ne “0” -and ($currentDate – $syncStatus).Days -gt 3) {
      # If the last sync was more than 3 days ago, initiate the sync via the scheduled task
      $taskName = “Microsoft Intune Enrollment Task”
      $taskPath = “\Microsoft\Windows\EnterpriseMgmt”
      $task = Get-ScheduledTask -TaskName $taskName -TaskPath $taskPath

      # Start the task and wait for it to complete
      Start-ScheduledTask -Task $task | Out-Null
      Get-ScheduledTaskInfo -TaskName $taskName -TaskPath $taskPath -Wait
      }

  • I am unable to make this work on W10 21H2 connected to Intuna and AutoPilot. The ‘PushLaunch’ task seems to do nothing, and launching ‘Schedule to run OMADMClient by client’ produces an error.

    But here are more things to use. Launching ‘Schedule #1 created by enrollment client’ runs ‘Schedule to run OMADMClient by client’ successfully.

    Kudos for doing great research.

    • the pushlaunch stuff was Michael Niehaus suggestion, and I have not played so much with it. my solution uses graph API and is different. please have a look at that if you are finding the other one does not work.
      Though this was written a long time ago and thing in security have changed and it might be less that ideal, it is still here on the blog for inspiration.

  • hi Michael,

    I’m not sure if you can help with this.
    Basically, I’ve ran other Michaels one liner as proactive remediation script to invoke the policy sync but i get error back as below:

    At C:\Windows\IMECache\HealthScripts\0b202fdb-c31e-4bcc-b927-88b3086c5091_2\detect.ps1:1 char:39 + Get-ScheduledTask | ? {$_.TaskName -eq �PushLaunch� } | Start-Sch … + ~ You must provide a value expression following the ‘-eq’ operator. At C:\Windows\IMECache\HealthScripts\0b202fdb-c31e-4bcc-b927-88b3086c5091_2\detect.ps1:1 char:40 + Get-ScheduledTask | ? {$_.TaskName -eq �PushLaunch� } | Start-Sch … + ~~~~~~~~~~~~~~~~ Unexpected token ‘�PushLaunch�’ in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ExpectedValueExpression

    When I upload the script, its properly with the single quotations:

    Get-ScheduledTask | ? {$_.TaskName -eq ‘PushLaunch’ } | Start-ScheduledTask

    When i save it and it runs, it changes the single quotation symbols to ¿½

    I’m new to this but love this topic as policy sync is an absolute pain in intune

    • Hi Pete,

      you have an encoding error.
      You should make sure the file is UTF-8 encoded and looking correct as UTF-8 before uploading.

  • You mentioned that there is a means to delete and re-apply Intune policies on an enrolled device. Do you have any details regarding those commands? Very interested in seeing if such commands could help resolve a policy compliance reporting issue I’ve come across.

  • Hi, can’t you just use this one?
    Get-ScheduledTask -TaskName “Schedule #3 created by enrollment client” | Start-ScheduledTask

    • Hi Pål

      Yes, that is also what Michael Niehaus has posted about, if you read the links in the update section at top of the article.

      But it still won’t work in the context of user if the person does not have admin rights.

  • Michael, we have approx 5000 systems and about 30 different compliance policies. ~4000 devices are failing compliance because of AV or Bitlocker. We want to enable Azure information protection and conditional access so I need to first get all these devices in compliance. I removed the bitlocker and av requirements in all 30 of our compliance policies (i added some settings back in configuration profiles). How can i get Intune to re-evaluate all 5000 systems against the changed policies?
    Thanks in advance.
    Lee

  • Hi Michael,

    Thanks for this post and the script.
    From my point of view the “classic” and even more ugly but more simple way of triggering a sync is to restart the IntuneManagementExtension service.
    Could you comment on why you chose not to do that?

    Cheers
    Klaus

    • Hi Klaus

      Thanks for a great question.

      First of all, the IME service is not a given on any Intune Enrolled Computer, though I am sure most will eventually have it.
      It’s only installed if there are PowerShell scripts or MSI/W32apps assigned to the device.

      Secondly, I have not been able to confirm that the restart of the service actually does a full policy update right away, I think it has different priorities.
      In any case, that was what I was initially doing, but this seemed to work better in my case, and I did not see anyone else sharing much on the matter, so I tought I would try my luck with it, and share the solution.

      Please do a Pull request to the GitHub repo if you have any other cool scripts that can help with Intune Sync 🙂

Sponsors