Invoke-ADConnect.ps1

<#
    .SYNOPSIS
 
    This function invokes AD Connect to sync the user if credentials were provided.
 
    .DESCRIPTION
 
    This function invokes AD Connect to sync the user if credentials were provided.
 
    .PARAMETER PowershellSessionName
 
    This is the name of the powershell session that will be used to trigger ad connect.
 
    .OUTPUTS
 
    Powershell session to use for aad connect commands.
 
    .EXAMPLE
 
    invoke-adConnect -powerShellSessionName NAME
 
    #>

    Function Invoke-ADConnect
     {
        [cmdletbinding()]

        Param
        (
            [Parameter(Mandatory = $true)]
            $PowershellSessionName
        )

        #Declare function variables.

        $workingPowershellSession=$null
        $invokeTest=$null
        $invokeSleep=$false

        #Start function processing.

        Out-LogFile -string "********************************************************************************"
        Out-LogFile -string "BEGIN INVOKE-ADCONNECT"
        Out-LogFile -string "********************************************************************************"

        #Log the parameters and variables for the function.

        Out-LogFile -string ("PowershellSessionName = "+$PowershellSessionName)

        #Obtain the powershell session to work with.

        try 
        {
            $workingPowershellSession = Get-PSSession -Name $PowershellSessionName
        }
        catch 
        {
            Out-LogFile -string $_ -isError:$TRUE
        }


        #Using the powershell session import the ad connect module.
    
        try 
        {
            invoke-command -session $workingPowershellSession -ScriptBlock {Import-Module -Name 'AdSync'}
        }
        catch 
        {
            Out-LogFile -string $_ -isError:$TRUE
        }

        do 
        {
            if ($invokeSleep -eq $TRUE)
            {
                out-logfile -string "Sleeping for 30 seconds."

                start-sleep -s 30
            }
            else 
            {
                out-logfile -string "This is first attempt - skipping sleep."

                $invokeSleep = $true
            }

            $invokeTest = Invoke-Command -Session $workingPowershellSession -ScriptBlock {start-adsyncsynccycle -policyType 'Delta'} *>&1

            if ($invokeTest.result -ne "Success")
            {
                out-logFile -string "An error has occured - this is not necessarily uncommon."
                out-logFile -string $invokeTest.exception.toString()
            }
            
        } until ($invokeTest.result -eq "Success")

        out-logfile -string "The results of the AD Sync."
        out-logfile -string $invokeTest.result

        Out-LogFile -string "ADConnect was successfully triggered."

        Out-LogFile -string "END INVOKE-ADCONNECT"
        Out-LogFile -string "********************************************************************************"
    }