Azure AD connect sync via Remote PowerShell

I wanted to initiate a remote sync of Azure AD connect via Remote PowerShell. The cmdlet is simple – Start-ADSyncSyncCycle -PolicyType Delta – but by default you can’t remove PowerShell unless you are an admin, and I didn’t want to open up admin access to a service account. Moreover I wanted to limit what the service account can do.

The solution for this is simple, and something I found via Google.

Step 1 – Create your service account

Step 2- Create a session configuration file on your Azure AD server.

For this, open an admin PowerShell window. And type the following:

New-PSSessionConfigurationFile `
  -ModulesToImport "C:\Program Files\Microsoft Azure AD Sync\Bin\ADSync" `
  -VisibleCmdLets ('Start-ADSyncSyncCycle') `
  -LanguageMode 'NoLanguage' `
  -SessionType 'RestrictedRemoteServer' `
  -Path 'c:\PSSessionConfigurationFile\limited-aad-sync.pssc'

This includes the AAD Sync module, and limits the visible cmdlets to a single one. The file is stored in the path given.

Step 3 – Register this session

In the same PowerShell window do:

Register-PSSessionConfiguration `
  -Name 'Limited AAD Sync' -ShowSecurityDescriptorUI `
  -Path 'c:\PSSessionConfigurationFile\limited-aad-sync.pssc'

This opens up a dialog box, wherein you can search and select the service account previously created. Give this Full Control rights. This is what allows the service account to connect using this session configuration. You could select a group too, but I prefer usernames so no one else can make changes unless they are on the Azure AD connect server.

And that’s it really!

From a client side if I were to now try and connect it would fail with an access denied message:

New-PSSession -ComputerName $server -Credential $creds

That’s because the service account isn’t a local admin. Try with the session configuration created above instead:

New-PSSession -ComputerName $server -Credential $creds -ConfigurationName "Limited AAD Sync"

This works! If I were to store the session in a variable, I can now run the sync cmdlet:

Invoke-Command -Session $session -ScriptBlock { Start-ADSyncSyncCycle -PolicyType delta }

Try any other cmdlet, and it will error out.

The above cmdlet too needs the service account to be in the “ADSyncOperators” groups on the Azure AD server. Else it will succeed but give the following error: Start-ADSyncSyncCycle: Retrieving the COM class factory for remote component with CLSID {835BEE60-8731-4159-8BFF-941301D76D05} from machine XXXX failed due to the following error: 80070005 XXXX.

That’s it! Easy peasy. Thanks to this Petri article for pointing me the right way.

This content was originally published here.