Sync-AAD.psm1
function Sync-AAD { <# .SYNOPSIS Initiates an Azure Active Directory Connect sync cycle on a remote server. .DESCRIPTION This function connects to a remote server and triggers an Azure Active Directory Connect sync cycle using the Start-ADSyncSyncCycle cmdlet. .PARAMETER ComputerName The name of the remote computer where the sync cycle should be initiated. .NOTES Author: Eric Meinders Version: 1.0 #> [cmdletbinding()] [Alias("Sync-ADToAAD", "Start-ADConnectSync")] param ( [parameter(Mandatory, Position=0, ValueFromPipeline)] [string]$ComputerName, [parameter(Position=1)] [System.Management.Automation.PSCredential] $Credential ) BEGIN { # Check if the remote computer is reachable if (!(Test-Connection -ComputerName $ComputerName -Count 1 -ErrorAction SilentlyContinue)) { Write-Host "Can't connect to " -ForegroundColor Yellow -NoNewline Write-Host "$ComputerName" -ForegroundColor Red return } # Define parameters for the Invoke-Command cmdlet $Parameters = @{ ComputerName = $ComputerName Credential = if ($Credential) { $Credential } else { (Get-Credential -Message "Please provide your ADM account credentials") } ScriptBlock = { Import-Module adsync Start-ADSyncSyncCycle -PolicyType Delta *> $null } } } PROCESS { # Invoke the command on the remote computer try { Invoke-Command @Parameters -Verbose -ErrorAction Stop $success = $true } catch { $success = $false Write-Host "$($Error[0].Exception.Message)" } } END { if ($success) { $output = "Sync completed on " $length = $output.Length + $ComputerName.Length $dashes = "-" * $length Write-Host "$dashes" Write-Host "$output" -ForegroundColor Green -NoNewline Write-Host "$ComputerName" -ForegroundColor Cyan Write-Host "$dashes" } } } |