Sync-UDElement works intermittently; can't figure the common denominator

Product: PowerShell Universal
Version: 4.1.8

I have a single page on a dashboard that takes a CSV file and imports the data changes to the Active Directory. Everything about my script is reliably functional.
Since the import can handle up to 1000 users per run. I wanted to give visual feedback to the user, so they know how the import was progressing. Before this, they would have to review a text file that I have it right to for whatever it is successful either importing or skipping for a user.

I decided to use a Modal that utilizes UDDynamic. When it works, it works perfectly. And no matter what, the AD updates commit no problem.

The problem is occasionally it says the Out-File Path is null.

The code that handles all this is mostly functions in a custom module I created. I thought having spaces in the file name was the problem because when I replaced whitespaces with hyphens. It was successful more often.

After more testing, it will often work for several script runs and sometimes without any change, it won’t grab the new file path even though I have it updating it for every run.

If it doesn’t do that, it will say it is null. Even though the first 2 or three lines of the log are committed by the code on the UDPage. What it has trouble with is the Out-Files in the module.

I cannot figure out what the issue is. I would appreciate any help anyone can provide. Thanks so much.

Code from the UDPage:

New-UDPage -Url "/ADImportADPCSVtoAD" -Name "AD Import ADP CSV to AD" -Content {
    New-UDForm -Id 'UDFImportADPCSVtoAD' -Content {
        New-UDTypography -Text 'Use this simple form to submit ADP CSV Export Files' -Variant h3
        New-UDTypography -Text 'THE DATA IN THE DOCUMENT WILL MAKE PERMANENT CHANGES TO THE ACTIVE DIRECTORY' -Variant subtitle1 -Style @{ color = 'red' }
        New-UDTypography -Text 'PLEASE CONFIRM THE DATA IN THE FILE BEFORE SUBMITTING' -Variant subtitle1 -Style @{ color = 'red' }
        New-UDUpload -Id 'UDUImportADPCSVtoAD' -Accept '.CSV' -OnUpload {
            $global:ADPCSVUploadBodyRawData = $null
            $global:ADPCSVUploadBodyRawData = $Body
            Clear-UDUImportADPCSVtoADUploader
            New-UDUImportADPCSVtoADUploader
        } -Text 'Upload ADP CSV File to Process'
    } -DisableSubmitOnEnter:$True -SubmitText 'COMMIT CHANGES TO AD' -OnSubmit {
        Update-TimestampAllFileNames
        Clear-ADPUserCSVVariableInfo
        Clear-ADUserVariableInfo
        #Clear-ADPPreADCSVFileName
        #Clear-ADPPostADCSVFileName
        #Clear-ADPCSVComparisonResultsFileNames
        Clear-ADPCSVFileVariableInfo
        Clear-ADPSubmittedCSVHeaderComparison
        Clear-LogfileVariableInfo
        Update-LogfileVariableInfo
        #New-ADPPreADCSVFileName
        #New-ADPPostADCSVFileName
        #New-ADPCSVComparisonResultsFileNames
        Update-ADPCSVFileVariableInfo
        Update-ADPSubmittedCSVHeaderComparison
        "INFO: ADP Import Process Started by User: $User at $global:LogfileTimestamp" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        "INFO: Log File Location on kvchs-pshell01.kvc.org - $global:LogfileExportPathandName" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        if ($global:ADPCSVHeaderNamesCompared.Count -gt 0) {
            Show-UDModal -Footer {
                New-UDButton -Text "TRY AGAIN" -OnClick {
                    Clear-AllADPImportGlobalVariables
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -Content {
                New-UDCard -Id 'UDCADCSVHeadCompResults' -Title "Header Comparison Problem" -Content {
                    New-UDTypography -Text { 'You have submitted a CSV file with invalid or missing headers, please confirm that all column titles (Headers) are present and are spelled correctly.' }
                    New-UDHtml -Markup "<br></br>"
                    New-UDTypography -Text { 'All headers must be present even if there is no data. The faulty headers that need checked are:' }
                    New-UDHtml -Markup "<br></br>"
                    $global:ADPCSVHeaderNamesCompared -join ", "
                }
                #Show-UDToast -Message $global:AllFileNameTimestamp -Duration 50000
                "ERROR: The ADP CSV file submitted for import was analyzed and was found to have improperly formatted column HEADERS. $($global:ADPCSVHeaderNamesCompared)" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            } -Persistent:$true
        }
        elseif ($global:ADPUserCSVDataMeasure.Count -eq 0) {
            Show-UDModal -Footer {
                New-UDButton -Text "TRY AGAIN" -OnClick {
                    #Show-UDToast -Message $global:AllFileNameTimestamp -Duration 50000
                    Clear-AllADPImportGlobalVariables
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -Content {
                "ERROR: The ADP CSV file submitted for import was analyzed and was found to have no users that could be processed." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
                New-UDTypography -Text 'You have submitted a CSV file that has no records in it, please choose a file with at least one user to process.'
            } -Persistent:$true
        }
        elseif (($global:ADPUserCSVDataMeasure.count -gt 0) -and ($global:ADPUserCSVDataMeasure.count -lt 1001)) {
            #Clear-ADPPreADCSVFileName
            #Clear-ADPPostADCSVFileName
            #Clear-ADPCSVComparisonResultsFileNames
            #Clear-ADPPreAndPostADAttributeValues
            #New-ADPPreADCSVFileName
            #New-ADPPostADCSVFileName
            #New-ADPCSVComparisonResultsFileNames
            #New-ADPADUpdatesPreImportArrayBuildForRef
            #New-ADPADUpdatesPostImportArrayBuildForDif
            Show-UDModal -Content {
                New-UDTypography -Text 'ADP Data is Now Importing' -Variant h3 -Style @{ color = 'green' }
                #Update-LogfileVariableInfo
                "INFO: The ADP CSV file submitted for import passed all validation tests. The users submitted will be updated." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
                Show-UDToast -Message $global:AllFileNameTimestamp -Duration 10000
                Show-UDToast -Message $global:LogfileExportPathandName -Duration 10000
                $page:ADPNumberOfUsersSubmitted = 0
                $page:ADPNumberOfUsersSubmitted = $global:ADPUserCSVDataMeasure.count
                $page:ADPNumberOfCurrentUserBeingProcessed = 0
                New-UDDynamic -Id 'UDDYADPImportProgressStatus' -Content {
                    $page:ADPImportProgressPercent = 0
                    $page:ADPImportProgressPercent = ($page:ADPNumberOfCurrentUserBeingProcessed / $page:ADPNumberOfUsersSubmitted) * 100
                    $page:ADPImportProgressPercent = [math]::Round($page:ADPImportProgressPercent)
                    $page:ADPImportProgressPercentCosmetic = $null
                    $page:ADPImportProgressPercentCosmetic = ($page:ADPNumberOfCurrentUserBeingProcessed / $page:ADPNumberOfUsersSubmitted).tostring("P")
                    New-UDTypography -Content { "The $page:ADPNumberOfUsersSubmitted users you submitted for update are now processing." } -Variant h4
                    New-UDProgress -PercentComplete $page:ADPImportProgressPercent
                    New-UDTypography -Content { "Percent Complete: $page:ADPImportProgressPercentCosmetic" } -Variant h4
                }
                New-UDDynamic -Id 'UDDYADPImportForEach' -Content {
                    foreach ($global:ADPUserCSV in $global:ADPUserCSVData) {
                        Update-ADPUserCSVVariableInfo
                        Update-ADUserVariableInfo
                        Update-ADUserADManagerVariableInfo
                        Clear-AllWorkTelephoneNumbers
                        Format-AllWorkTelephoneNumbers
                        Update-ADUserAtrributesFromADPCSV
                        $page:ADPNumberOfCurrentUserBeingProcessed++
                        Sync-UDElement -Id 'UDDYADPImportProgressStatus'
                    }
                }
            } -Footer {
                New-UDButton -Text "START OVER" -OnClick { 
                    Clear-AllADPImportGlobalVariables
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -FullScreen:$true -Persistent:$true
        }
        elseif ($global:ADPUserCSVDataMeasure.count -gt 1000) {
            Show-UDModal -Footer {
                New-UDButton -Text "TRY AGAIN" -OnClick {
                    Clear-AllADPImportGlobalVariables
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -Content {
                #Show-UDToast -Message $global:AllFileNameTimestamp -Duration 50000
                "ERROR: The ADP CSV file submitted for import was analyzed and was found to have $($global:ADPUserCSVDataMeasure.count) Users to be processed. This exceeds the allowable amount of 1000 total users per import." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
                New-UDTypography -Text 'You have submitted a CSV file that exceeds the maximum allowable objects to update at one time. Please reduce the amount of records you wish to update to 1000 or less and try again.'
            } -Persistent:$true
        }
        else {
            Show-UDModal -Footer {
                New-UDButton -Text "TRY AGAIN" -OnClick { 
                    Clear-AllADPImportGlobalVariables
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -Content {
                "ERROR: The ADP CSV file submitted for import was analyzed and though it passed all the validation checks, something went wrong. All the powershell errors for this session should be reported on the next line." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
                "SYSTEMERROR: $Error"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
                New-UDTypography -Text 'You have submitted a CSV file that is unable to validate. Please confirm the format and values and try again.'
            } -Persistent:$true
        }
    } -CancelText 'ABORT IMPORT' -OnCancel {
        #If (Test-Path -Path $global:ADPUploadFrmFPathPlusFName -ErrorAction SilentlyContinue) { Remove-Item -Path $global:ADPUploadFrmFPathPlusFName -Force }
        Clear-LogfileVariableInfo
        Update-TimestampAllFileNames
        Update-LogfileVariableInfo
        "INFO: The import process was aborted by the user: $User" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        Clear-AllADPImportGlobalVariables
        Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
    }
    New-UDTypography -Id 'UDTYPOLinktoADPFiles' -Align right -Content {
        New-UDLink -Text 'ADP Import Diagnostic Files' -Url https://putility.kvc.org/ADPImportScript-SystemFolder-WebShare -Variant h4 -OpenInNewWindow
    } -GutterBottom
}

LEt me know if I can provide anything else. Thank you to anyone who can give any guidance.

Code from the Module:

function Clear-AllADPImportGlobalVariables {
    Clear-Variable -Name AD* -Scope Global -Force
    Clear-Variable -Name Log* -Scope Global -Force
    Clear-Variable -Name CSV* -Scope Global -Force
    Clear-Variable -Name Import* -Scope Global -Force
}
function Update-TimestampAllFileNames {
    $global:AllFileNameTimestamp = $null
    $global:AllFileNameTimestamp = Get-Date -Format 'yyyy-MM-dd-hh-mm-ss'
}
function Clear-UDUImportADPCSVtoADUploader {
    $global:ADPUploadFrmData = $null 
    $global:ADPUploadFrmJSONBytes = $null
    $global:ADPUploadFrmFileName = $null
    $global:ADPUploadFrmFolderPath = $null
    $global:ADPUploadFrmFPathPlusFName = $null
}
function New-UDUImportADPCSVtoADUploader {
    $global:ADPUploadFrmFileNameTimestamp = $null
    $global:ADPUploadFrmFileNameTimestamp = Get-Date -Format 'yyyy-MM-dd-hh-mm-ss'
    $global:ADPUploadFrmData = $global:ADPCSVUploadBodyRawData | ConvertFrom-Json 
    $global:ADPUploadFrmJSONBytes = [System.Convert]::FromBase64String($global:ADPUploadFrmData.Data)
    $global:ADPUploadFrmFileName = $global:ADPUploadFrmData.Name
    $global:ADPUploadFrmFolderPath = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\ADPData"
    If (-not (Test-Path -Path $global:ADPUploadFrmFolderPath -ErrorAction SilentlyContinue)) {
        # Folder does not exist, create it
        New-Item -Path $global:ADPUploadFrmFolderPath -ItemType Directory -Force
    }
    $global:ADPUploadFrmFPathPlusFName = "$global:ADPUploadFrmFolderPath\$global:ADPUploadFrmFileNameTimestamp-$global:ADPUploadFrmFileName"
    [System.IO.File]::WriteAllBytes($global:ADPUploadFrmFPathPlusFName, $global:ADPUploadFrmJSONBytes)
}
Function Clear-LogfileVariableInfo {
    #Null out log file variables
    #$global:LogfileRootFolderPath = $Null
    $global:LogfileExportFileName = $null
    $global:LogfileExportPathandName = $null
}
Function Update-LogfileVariableInfo {
    $global:LogfileTimestamp = $null
    $global:LogfileTimestamp = $global:AllFileNameTimestamp
    $global:LogfileRootFolderPath = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\ADPLogs\"
    $global:LogfileExportFileName = 'ADPSync-Log-' + $global:LogfileTimestamp + '.txt'
    $global:LogfileExportPathandName = $global:LogfileRootFolderPath + $global:LogfileExportFileName
}
Function Clear-ADPCSVFileVariableInfo {
    #null out these variables
    $global:ADPCSVDataRootFolderPath = $null
    $global:ADPCSVLatestDataFile = $null
    $global:ADPCSVLatestDataFileName = $null
    #variables for CSV file handling
    $global:ADPUserCSVData = $null
}
Function Update-ADPCSVFileVariableInfo {    
    #Parse for newest ADP file
    $global:ADPCSVDataRootFolderPath = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\ADPData\"
    $global:ADPCSVLatestDataFile = Get-ChildItem $global:ADPCSVDataRootFolderPath -Filter *.csv | sort LastWriteTime | select -Last 1
    $global:ADPCSVLatestDataFileName = $global:ADPCSVLatestDataFile.FullName
    #commented to test using different file
    $global:ADPUserCSVData = Import-Csv $global:ADPCSVLatestDataFileName
    #This is the temp replacement
    #$global:ADPUserCSVData = Import-Csv $global:ADPUploadFrmFPathPlusFName
}
function Clear-ADPSubmittedCSVHeaderComparison {
    $global:ADPUserCSVDataMeasure = $null
    #array for submitted file compare variables
    $global:ADPCSVHeaderNamesObjCompareDif = @()
    $global:ADPCSVHeaderNamesCompared = $null
    #Array Headers that should be present in the submitted CSV
    $global:ADPCSVHeaderNamesObjCompareRef = @()
    $global:ADPCSVHeaderNamesObjCompareRef = @('Associate ID', 'File Number', 'Hire/Rehire Date', 'Home Department Code', 'Home Department Description', 'Job Title Description', 'Legal First Name', 'Legal Last Name', 'Location Description', 'Payroll Company Code', 'Personal Contact: Personal Mobile', 'Position ID', 'Position Status', 'Preferred or Chosen First Name', 'Professional Suffix Code', 'Pronouns', 'Reports To Associate ID', 'Reports To Name', 'Termination Date', 'Work Address: Address Line 1', 'Work Address: City', 'Work Address: State / Territory Code', 'Work Address: Zip / Postal Code', 'Work Contact: Work Email', 'Work Contact: Work Fax', 'Work Contact: Work Mobile', 'Work Contact: Work Phone', 'Worker Category Description')
}
function Update-ADPSubmittedCSVHeaderComparison {
    $global:ADPUserCSVDataMeasure = $global:ADPUserCSVData | Measure-Object
    $global:ADPCSVHeaderNamesObjCompareDif = ($global:ADPUserCSVData | Get-Member -MemberType NoteProperty -ErrorAction SilentlyContinue).Name
    try { 
        $global:ADPCSVHeaderNamesCompared = Compare-Object -ReferenceObject $global:ADPCSVHeaderNamesObjCompareRef -DifferenceObject $global:ADPCSVHeaderNamesObjCompareDif -CaseSensitive -PassThru
    }
    catch {
    }
}
Function Clear-ADPUserCSVVariableInfo {
    #Null variables used to hold csv values
    $global:ADPUserAssocID = $null
    $global:ADPUserJobTitle = $null
    $global:ADPUserFileNumber = $null
    $global:ADPUserOffice = $null
    $global:ADPUserDepartment4Digit = $null
    $global:ADPUserDepartmentDescript = $null
    $global:ADPUserReportToManager = $null
    $global:ADPUserWorkOfficeNum = $null
    $global:ADPUserWorkMobileNum = $null
    $global:ADPUserWorkFacsimileNum = $null
    $global:ADPUserStreetAddress = $null
    $global:ADPUserCity = $null
    $global:ADPUserState = $null
    $global:ADPUserPostalCode = $null
    $global:ADPUserHireDate = $null
    $global:ADPUserTermDate = $null
    #Declare array for list of users to export to CSV
    $global:ADPProcessedUserAssocIdArray = @()
}
Function Update-ADPUserCSVVariableInfo {
    $global:ADPUserAssocID = $global:ADPUserCSV.'Associate ID'
    $global:ADPUserJobTitle = $global:ADPUserCSV.'Job Title Description'
    $global:ADPUserFileNumber = $global:ADPUserCSV.'File Number'
    $global:ADPUserOffice = $global:ADPUserCSV.'Location Description'
    $global:ADPUserDepartment4Digit = $global:ADPUserCSV.'Home Department Code'
    $global:ADPUserDepartmentDescript = $global:ADPUserCSV.'Home Department Description'
    $global:ADPUserReportToManager = $global:ADPUserCSV.'Reports To Associate ID'
    $global:ADPUserWorkOfficeNum = $global:ADPUserCSV.'Work Contact: Work Phone'
    $global:ADPUserWorkMobileNum = $global:ADPUserCSV.'Work Contact: Work Mobile'
    $global:ADPUserWorkFacsimileNum = $global:ADPUserCSV.'Work Contact: Work Fax'
    $global:ADPUserStreetAddress = $global:ADPUserCSV.'Work Address: Address Line 1'
    $global:ADPUserCity = $global:ADPUserCSV.'Work Address: City'
    $global:ADPUserState = $global:ADPUserCSV.'Work Address: State / Territory Code'
    $global:ADPUserPostalCode = $global:ADPUserCSV.'Work Address: Zip / Postal Code'
    $global:ADPUserHireDate = $global:ADPUserCSV.'Hire/Rehire Date'
    $global:ADPUserTermDate = $global:ADPUserCSV.'Termination Date'
    #format FileNumber and Dept Code
    if (($global:ADPUserDepartment4Digit).tostring().length -gt 4) { $global:ADPUserDepartment4Digit = $global:ADPUserDepartment4Digit -replace '^0+(?=[^.])', '' }
    if (($global:ADPUserFileNumber).tostring().length -gt 5) { $global:ADPUserFileNumber = $global:ADPUserFileNumber -replace '^0+(?=[^.])', '' }
    #Build AssocID Array
    $global:ADPProcessedUserAssocIdArray += $global:ADPUserAssocID
}
function Clear-ADUserVariableInfo {
    #null pre and post user array dumps
    $global:CSVComparisonPreADPDataImport = @()
    $global:CSVComparisonPostADPDataImport = @()
    #Null variable that holds user to process
    $global:ADUserActDirData = $null
    #null Attributes for handling a users manager setting
    $global:ADPADUserReportsToManagerDistName = $null
    #Null sub-variables that holds user specific sub-variables
    $global:ADUserEmployeeID = $null
    $global:ADUserPrincipalName = $null
    $global:ADUserAccountExpirationDate = $null
    $global:ADUserJobTitle = $null
    $global:ADUserDepartmentDescript = $null
    $global:ADUserPDON = $null
    $global:ADUserWorkOfficeNum = $null
    $global:ADUserWorkMobileNum = $null
    $global:ADUserWorkFacsimileNum = $null
    $global:ADUserStreetAddress = $null
    $global:ADUserCity = $null
    $global:ADUserState = $null
    $global:ADUserPostalCode = $null
    #extensionAttribute5 is the users Department Description; until the dynamic groups are updated this has to stay numeric
    $global:ADUserExtAttrib5 = $null
    #extensionAttribute6 is the users ADP File Number
    $global:ADUserExtAttrib6 = $null
    #extensionAttribute7 is the users Hire Date
    $global:ADUserExtAttrib7 = $null
    #extensionAttribute8 is the users Termination Date
    $global:ADUserExtAttrib8 = $null
    #extensionAttribute15 is the users Telephone Number attribute but formatted to be used in the email signature
    $global:ADUserExtAttrib15 = $null
}
Function Update-ADUserADManagerVariableInfo {
    $global:ADUserADManagerPulledFromAD = $null
    try {
        $global:ADUserADManagerPulledFromAD = Get-ADUser -LDAPFilter “(employeeID=$global:ADPUserReportToManager)” -Properties sAMAccountName, userPrincipalName, DistinguishedName | Select-Object sAMAccountName, userPrincipalName, DistinguishedName
    }
    catch {
        "PROCESSING: $global:ADUserPrincipalName has no manager set in the AD." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
}
Function Update-ADUserVariableInfo {
    $global:ADUserActDirData = Get-ADUser -LDAPFilter “(employeeID=$global:ADPUserAssocID)” -Properties sAMAccountName, employeeID, userPrincipalName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 -Server kvc.org | Select-Object -Property sAMAccountName, userPrincipalName, employeeID, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15
    $global:ADPADUserReportsToManagerDistName = $global:ADUserActDirData.manager
    $global:ADUserEmployeeID = $global:ADUserActDirData.employeeID
    $global:ADUserPrincipalName = $global:ADUserActDirData.userPrincipalName
    $global:ADUserAccountExpirationDate = $global:ADUserActDirData.accountExpirationDate
    $global:ADUserJobTitle = $global:ADUserActDirData.Title
    $global:ADUserDepartmentDescript = $global:ADUserActDirData.Department
    $global:ADUserPDON = $global:ADUserActDirData.physicalDeliveryOfficeName
    $global:ADUserWorkOfficeNum = $global:ADUserActDirData.telephoneNumber
    $global:ADUserWorkMobileNum = $global:ADUserActDirData.mobile
    $global:ADUserWorkFacsimileNum = $global:ADUserActDirData.facsimileTelephoneNumber
    $global:ADUserStreetAddress = $global:ADUserActDirData.StreetAddress
    $global:ADUserCity = $global:ADUserActDirData.city
    $global:ADUserState = $global:ADUserActDirData.st
    $global:ADUserPostalCode = $global:ADUserActDirData.postalCode
    $global:ADUserExtAttrib5 = $global:ADUserActDirData.extensionAttribute5
    $global:ADUserExtAttrib6 = $global:ADUserActDirData.extensionAttribute6
    $global:ADUserExtAttrib7 = $global:ADUserActDirData.extensionAttribute7
    $global:ADUserExtAttrib8 = $global:ADUserActDirData.extensionAttribute8
    $global:ADUserExtAttrib15 = $global:ADUserActDirData.extensionAttribute15
    #$global:CSVComparisonPreADPDataImport += $global:ADUserActDirData
}
Function Clear-AllWorkTelephoneNumbers {
    #Null variables for phone number fomatting
    $global:ADPUserWorkOfficeNumFormatted = $null
    $global:ADPUserWorkMobileNumFormatted = $null
    $global:ADPUserWorkFacsimileNumFormatted = $null
    $global:ADPUserWorkOfficeNumFormattedForSignature = $null
}
Function Format-AllWorkTelephoneNumbers {
    #working format command but a bit complicated
    $global:ADPUserWorkOfficeNumFormatted = $global:ADPUserWorkOfficeNum -replace "[^0-9]", "" -replace "^1(\d{10})$", '$1' -replace "(\d{3})(\d{3})(\d{4})", '+1$1$2$3'
    $global:ADPUserWorkMobileNumFormatted = $global:ADPUserWorkMobileNum -replace "[^0-9]", "" -replace "^1(\d{10})$", '$1' -replace "(\d{3})(\d{3})(\d{4})", '$1-$2-$3'
    $global:ADPUserWorkFacsimileNumFormatted = $global:ADPUserWorkFacsimileNum -replace "[^0-9]", "" -replace "^1(\d{10})$", '$1' -replace "(\d{3})(\d{3})(\d{4})", '$1-$2-$3'
    $global:ADPUserWorkOfficeNumFormattedForSignature = $global:ADPUserWorkOfficeNum -replace "[^0-9]", "" -replace "^1(\d{10})$", '$1' -replace "(\d{3})(\d{3})(\d{4})", '$1-$2-$3'
}
Function Clear-ADPPreADCSVFileName {
    #null out Pre-Import Variables
    $global:CSVPreComparisonRootFolderPath = $null
    $global:CSVPreComparisonFileName = $null
    $global:CSVPreComparisonPathandName = $null
}
Function New-ADPPreADCSVFileName {
    $global:CSVPreCompFileTimestamp = $null
    $global:CSVPreCompFileTimestamp = $global:AllFileNameTimestamp
    #set Pre-Import path and file name info
    $global:CSVPreComparisonRootFolderPath = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\Pre-ADPtoADUserUpdateRecord\"
    $global:CSVPreComparisonFileName = 'Pre-ProcessedADUserAttributeValues-' + $global:CSVPreCompFileTimestamp + '.csv'
    $global:CSVPreComparisonPathandName = $global:CSVPreComparisonRootFolderPath + $global:CSVPreComparisonFileName    
}
Function Clear-ADPPostADCSVFileName {
    #null out Post-Import Variables
    $global:CSVPostComparisonRootFolderPath = $null
    $global:CSVPostComparisonFileName = $null
    $global:CSVPostComparisonPathandName = $null
}
Function New-ADPPostADCSVFileName {
    $global:CSVPostCompFileTimestamp = $null
    $global:CSVPostCompFileTimestamp = $global:AllFileNameTimestamp
    #set Post-Import path and file name info
    $global:CSVPostComparisonRootFolderPath = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\Post-ADPtoADUserUpdateRecord\"
    $global:CSVPostComparisonFileName = 'Post-ProcessedADUserAttributeValues-' + $global:CSVPostCompFileTimestamp + '.csv'
    $global:CSVPostComparisonPathandName = $global:CSVPostComparisonRootFolderPath + $global:CSVPostComparisonFileName
    
}
Function Clear-ADPCSVComparisonResultsFileNames {
    #null out Post-Import Variables
    $global:CSVCompareResultsRootFolderPath = $null
    $global:CSVCompareResultsFileName = $null
    $global:CSVCompareResultsPathandName = $null
}
Function New-ADPCSVComparisonResultsFileNames {
    $global:CSVCompareResultFileTimestamp = $null
    $global:CSVCompareResultFileTimestamp = $global:AllFileNameTimestamp
    #set Pre-Import path and file name info
    $global:CSVCompareResultsRootFolderPath = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\ADPADChangeComparisonResults\"
    $global:CSVCompareResultsFileName = 'ProcessedADUserAttributeValuesCompared-' + $global:CSVCompareResultFileTimestamp + '.csv'
    $global:CSVCompareResultsPathandName = $global:CSVCompareResultsRootFolderPath + $global:CSVCompareResultsFileName
}
Function New-ADPADUpdatesPreImportArrayBuildForRef {
    $PreProcessedADUser = $null
    foreach ($PreProcessedADUser in $global:CSVComparisonPreADPDataImport) {
        $PreProcessedADUser | Select-Object -Property employeeID, userPrincipalName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 | Sort-Object -Property userPrincipalName | Export-Csv -Path $global:CSVPreComparisonPathandName -NoTypeInformation -NoClobber -Append
    }
}
Function New-ADPADUpdatesPostImportArrayBuildForDif {
    $PostProcessedADUser = $null
    foreach ($PostProcessedADUser in $global:CSVComparisonPostADPDataImport) {
        $PostProcessedADUser | Select-Object -Property employeeID, userPrincipalName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 | Sort-Object -Property userPrincipalName | Export-Csv -Path $global:CSVPostComparisonPathandName -NoTypeInformation -NoClobber -Append
    }
}
Function Clear-ADPPreAndPostADAttributeValues {
    $global:CSVPreRefValCompPostDifVals = @()
    $global:CSVCompareResultsPSOValues = $null
    $global:CSVArrayOfCompareResults = @()
    $global:CSVPreRecordIndexValue = 0
    $global:CSVPostRecordIndexValue = 0
    $global:ImportEmployeeTitleChange = $null
    $global:ImportEmployeeDepartmentChange = $null
    $global:ImportEmployeephysDelivOffNameChange = $null
    $global:ImportEmployeeTelephoneNumChange = $null
    $global:ImportEmployeeMobileNumChange = $null
    $global:ImportEmployeeFaxNumChange = $null
    $global:ImportEmployeeStreetAddrChange = $null
    $global:ImportEmployeeCityChange = $null
    $global:ImportEmployeeStateChange = $null
    $global:ImportEmployeePostalCodeChange = $null
    $global:ImportEmployeeManagerChange = $null
    $global:ImportEmployeeAccountExpirationChange = $null
    $global:ImportEmployeeextAttrib5Change = $null
    $global:ImportEmployeeextAttrib6Change = $null
    $global:ImportEmployeeextAttrib7Change = $null
    $global:ImportEmployeeextAttrib8Change = $null
    $global:ImportEmployeeextAttrib15Change = $null
}
Function Compare-ADPPreAndPostADAttributeValues {
    $CSVCompareResult = $null
    $CSVPreComparisonFileImport = $null
    $CSVPostComparisonFileImport = $null
    $CSVPreComparisonFileImport = Import-Csv -Path $global:CSVPreComparisonPathandName
    $CSVPostComparisonFileImport = Import-Csv -Path $global:CSVPostComparisonPathandName

    $global:CSVPreRefValCompPostDifVals = Compare-Object -ReferenceObject @($CSVPreComparisonFileImport | Select-Object) -DifferenceObject @($CSVPostComparisonFileImport | Select-Object) -Property employeeID, userPrincipalName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 -CaseSensitive -PassThru | Where-Object { $_.SideIndicator -eq "=>" }

    Foreach ($CSVCompareResult in $global:CSVPreRefValCompPostDifVals) {
        $global:CSVPreRecordIndexValue = [Array]::IndexOf($CSVPreComparisonFileImport.employeeID, $CSVCompareResult.employeeID)
        $global:CSVPostRecordIndexValue = [Array]::IndexOf($CSVPostComparisonFileImport.employeeID, $CSVCompareResult.employeeID)
        
        $global:ImportEmployeeTitleChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].title) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].title)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].title } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].title + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].title }
        $global:ImportEmployeeDepartmentChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].department) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].department)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].department } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].department + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].department }
        $global:ImportEmployeephysDelivOffNameChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].physicalDeliveryOfficeName) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].physicalDeliveryOfficeName)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].physicalDeliveryOfficeName } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].physicalDeliveryOfficeName + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].physicalDeliveryOfficeName }
        $global:ImportEmployeeTelephoneNumChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].telephoneNumber) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].telephoneNumber)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].telephoneNumber } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].telephoneNumber + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].telephoneNumber }
        $global:ImportEmployeeMobileNumChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].mobile) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].mobile)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].mobile } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].mobile + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].mobile }
        $global:ImportEmployeeFaxNumChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].facsimileTelephoneNumber) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].facsimileTelephoneNumber)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].facsimileTelephoneNumber } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].facsimileTelephoneNumber + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].facsimileTelephoneNumber }
        $global:ImportEmployeeStreetAddrChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].streetAddress) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].streetAddress)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].streetAddress } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].streetAddress + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].streetAddress }
        $global:ImportEmployeeCityChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].city) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].city)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].city } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].city + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].city }
        $global:ImportEmployeeStateChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].st) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].st)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].st } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].st + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].st }
        $global:ImportEmployeePostalCodeChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].postalCode) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].postalCode)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].postalCode } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].postalCode + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].postalCode }
        $global:ImportEmployeeManagerChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].manager) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].manager)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].manager } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].manager + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].manager }
        $global:ImportEmployeeAccountExpirationChange = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].accountExpirationDate) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].accountExpirationDate)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].accountExpirationDate } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].accountExpirationDate + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].accountExpirationDate }
        $global:ImportEmployeeextAttrib5Change = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute5) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute5)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute5 } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute5 + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute5 }
        $global:ImportEmployeeextAttrib6Change = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute6) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute6)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute6 } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute6 + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute6 }
        $global:ImportEmployeeextAttrib7Change = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute7) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute7)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute7 } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute7 + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute7 }
        $global:ImportEmployeeextAttrib8Change = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute8) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute8)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute8 } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute8 + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute8 }
        $global:ImportEmployeeextAttrib15Change = if (($CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute15) -eq ($CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute15)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute15 } else { "Previous Value: " + $CSVPreComparisonFileImport[$global:CSVPreRecordIndexValue].extensionAttribute15 + " | Updated Value: " + $CSVPostComparisonFileImport[$global:CSVPostRecordIndexValue].extensionAttribute15 }

        $global:CSVCompareResultsPSOValues = [pscustomobject][ordered] @{
            employeeID                 = $CSVCompareResult.employeeID
            userPrincipalName          = $CSVCompareResult.userPrincipalName
            title                      = $global:ImportEmployeeTitleChange
            department                 = $global:ImportEmployeeDepartmentChange
            physicalDeliveryOfficeName = $global:ImportEmployeephysDelivOffNameChange
            telephonenumber            = $global:ImportEmployeeTelephoneNumChange
            mobile                     = $global:ImportEmployeeMobileNumChange
            facsimileTelephoneNumber   = $global:ImportEmployeeFaxNumChange
            streetAddress              = $global:ImportEmployeeStreetAddrChange
            city                       = $global:ImportEmployeeCityChange
            st                         = $global:ImportEmployeeStateChange
            postalCode                 = $global:ImportEmployeePostalCodeChange
            manager                    = $global:ImportEmployeeManagerChange
            accountExpirationDate      = $global:ImportEmployeeAccountExpirationChange
            extensionAttribute5        = $global:ImportEmployeeextAttrib5Change
            extensionAttribute6        = $global:ImportEmployeeextAttrib6Change
            extensionAttribute7        = $global:ImportEmployeeextAttrib7Change
            extensionAttribute8        = $global:ImportEmployeeextAttrib8Change
            extensionAttribute15       = $global:ImportEmployeeextAttrib15Change
        }
        $global:CSVArrayOfCompareResults += $global:CSVCompareResultsPSOValues
        $global:CSVCompareResultsPSOValues | Select-Object employeeID, userPrincipalName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 | Export-Csv -Path $global:CSVCompareResultsPathandName -Append -NoClobber -NoTypeInformation
    }
}
Function Update-ADUserAtrributesFromADPCSV {
    
    "PROCESSING: $global:ADUserPrincipalName ..." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    #Process Users Job Title
    if ($global:ADPUserJobTitle -eq '') {
        "BLANK: The Users Job Title in ADP is blank. No changes will be made to the user's Job Title attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserJobTitle -ne $global:ADUserActDirData.title) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Title $global:ADPUserJobTitle -Server kvc.org
            "UPDATING: Title $global:ADUserJobTitle will be overwritten with value $global:ADPUserJobTitle" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users title attribute value with the following data: $global:ADPUserJobTitle Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
    }
    else {
        "NOCHANGE: The Users ADP Job Title information in ADP already matches the AD objects Title attribute value: ADP Value = $global:ADPUserJobTitle <==> AD Value = $global:ADUserJobTitle" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    
    #Process Users File Number
    if ($global:ADPUserFileNumber -eq '') {
        "BLANK: The Users File Number in ADP is blank. No changes will be made to the user's File Number-(extensionAttribute6) attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserFileNumber -ne $global:ADUserActDirData.extensionAttribute6) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Replace @{"extensionAttribute6" = $global:ADPUserFileNumber } -Server kvc.org
            "UPDATING: File Number-(extensionAttribute6) $global:ADUserExtAttrib6 will be overwritten with value $global:ADPUserFileNumber" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users extensionAttribute6 attribute value with the following data: $global:ADPUserFileNumber Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }     
    }
    else {
        "NOCHANGE: The Users ADP File Number-(extensionAttribute6) information in ADP already matches the AD objects File Number-(extensionAttribute6) attribute value: ADP Value = $global:ADPUserFileNumber <==> AD Value = $global:ADUserExtAttrib6" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
       
    #Process Users 4 Digit Department Code
    if ($global:ADPUserDepartment4Digit -eq '') {
        "BLANK: The Users 4-Digit Department Code in ADP is blank. No changes will be made to the 4-Digit Department Code-(extensionAttribute5) attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserDepartment4Digit -ne $global:ADUserActDirData.extensionAttribute5) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Replace @{"extensionAttribute5" = $global:ADPUserDepartment4Digit } -Server kvc.org
            "UPDATING: 4-Digit Department Code-(extensionAttribute5) $global:ADUserExtAttrib5 will be overwritten with value $global:ADPUserDepartment4Digit" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users extensionAttribute5 attribute value with the following data: $global:ADPUserDepartment4Digit Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
    }
    else {
        "NOCHANGE: The Users 4-Digit Department Code-(extensionAttribute5) information in ADP already matches the AD objects 4-Digit Department Code-(extensionAttribute5) attribute value: ADP Value = $global:ADPUserDepartment4Digit <==> AD Value = $global:ADUserExtAttrib5" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users Department Description
    if ($global:ADPUserDepartmentDescript -eq '') {
        "BLANK: The Users Department Name in ADP is blank. No changes will be made to the Department attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }   
    elseif ($global:ADPUserDepartmentDescript -ne $global:ADUserActDirData.department) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Department $global:ADPUserDepartmentDescript -Server kvc.org
            "UPDATING: Department $global:ADUserDepartmentDescript will be overwritten with value $global:ADPUserDepartmentDescript" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users department attribute value with the following data: $global:ADPUserDepartmentDescript Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
    }
    else {
        "NOCHANGE: The Users Department Name information in ADP already matches the AD objects Department attribute value: ADP Value = $global:ADPUserDepartmentDescript <==> AD Value = $global:ADUserDepartmentDescript" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users HireDate
    if ($global:ADPUserHireDate -eq '') {
        "BLANK: The Users Hire Date in ADP is blank. No changes will be made to the Hire Date-(extensionAttribute7) attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }    
    elseif ($global:ADPUserHireDate -ne $global:ADUserActDirData.extensionAttribute7) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Replace @{"extensionAttribute7" = $global:ADPUserHireDate } -Server kvc.org
            "UPDATING: HireDate $global:ADUserExtAttrib7 will be overwritten with value $global:ADPUserHireDate" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users Hire Date-(extensionAttribute7) attribute value with the following data: $global:ADPUserHireDate Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
    }
    else {
        "NOCHANGE: The Users Hire Date-(extensionAttribute7) information in ADP already matches the AD objects Hire Date-(extensionAttribute7) attribute value: ADP Value = $global:ADPUserHireDate <==> AD Value = $global:ADUserExtAttrib7" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users Termination Date
    if ($global:ADPUserTermDate -eq '') {
        "BLANK: The Users Term Date in ADP is blank. No changes will be made to the Term Date-(extensionAttribute8) attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserTermDate -ne $global:ADUserActDirData.extensionAttribute8) {
        #Declare Variable for PArseExact DateTime MM/DD/YYYY
        $page:ADUserUpdateAccountExpirDateFormat = "MM/dd/yyyy"
        $page:ADUserAccountExpirationDateFormatted = $null
        $page:ADUserAccountExpirationDateFormatted = [datetime]::ParseExact($global:ADPUserTermDate, "M/dd/yyyy", $null).ToString($page:ADUserUpdateAccountExpirDateFormat)
        #Now that the Termination date from ADP has been formatted, set the both Term Date attribs for user
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Replace @{"extensionAttribute8" = $global:ADPUserTermDate } -Server kvc.org
            "UPDATING: The Users Employment Termination Date-(extensionAttribue8) $global:ADUserExtAttrib8 will be overwritten with value $global:ADPUserTermDate" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            Set-ADAccountExpiration -Identity $global:ADUserActDirData.sAMAccountName -DateTime $page:ADUserAccountExpirationDateFormatted -Confirm:$False -Server kvc.org
            "UPDATING: The Users Employment Termination Date-(accountExpirationDate) $global:ADUserAccountExpirationDate will be overwritten with value $global:ADPUserTermDate" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users Termination Date-(extensionAttribue8) and Termination Date-(accountExpirationDate) attribute value with the following data: $global:ADPUserTermDate Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
    }
    else {
        "NOCHANGE: The Users Employment Term Date-(extensionAttribute8) information in ADP already matches the AD objects Term Date-(extensionAttribute8) attribute value:  ADP Value = $global:ADPUserTermDate <==> AD Value = $global:ADUserExtAttrib8" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users Office Name
    if ($global:ADPUserOffice -eq '') {
        "BLANK: The Users Office Name in ADP is blank. No changes will be made to the physicalDeliveryOfficeName attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }        
    elseif ($global:ADPUserOffice -ne $global:ADUserActDirData.physicalDeliveryOfficeName) {
        try {
            #Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Office $global:ADPUserOffice -Server kvc.org -WhatIf
            #"UPDATING: Office $global:ADUserPDON will be overwritten with value $global:ADPUserOffice" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users physicalDeliveryOfficeName attribute value with the following data: $global:ADPUserOffice Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }        
    }
    else {
        "NOCHANGE: The Users Office Name information in ADP already matches the AD objects physicalDeliveryOfficeName attribute value: ADP Value = $global:ADPUserOffice <==> AD Value = $global:ADUserPDON" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }    
    #Process Users Work Telephone Number        
    if ($global:ADPUserWorkOfficeNumFormatted -eq '') {
        "BLANK: The Users Work Office Number in ADP is blank. No changes will be made to the telephoneNumber or extensionAttribute15 attribute values." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        #Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Clear TelephoneNumber, extensionAttribute15 -Server kvc.org
    }
    elseif ($global:ADPUserWorkOfficeNumFormatted -ne $global:ADUserWorkOfficeNum) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -OfficePhone $global:ADPUserWorkOfficeNumFormatted -Replace @{"extensionAttribute15" = $global:ADPUserWorkOfficeNumFormattedForSignature } -Server kvc.org
            "UPDATING: Work phone $global:ADUserWorkOfficeNum will be overwritten with value $global:ADPUserWorkOfficeNumFormatted" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "UPDATING: extensionAttribute15 $global:ADUserExtAttrib15 will be overwritten with value $global:ADPUserWorkOfficeNumFormattedForSignature" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users telephoneNumber and extensionAttribute15 attribute value with the following data: $global:ADPUserWorkOfficeNumFormatted and $global:ADPUserWorkOfficeNumFormattedForSignature Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }        
    }
    else {
        "NOCHANGE: The Users Work Office Number information in ADP already matches the AD objects telephoneNumber attribute value: ADP Value = $global:ADPUserWorkOfficeNumFormatted <==> AD Value = $global:ADUserWorkOfficeNum" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }     
    #Process Users Work Mobile Number      
    if ($global:ADPUserWorkMobileNumFormatted -eq '') {
        "BLANK: The Users Work Mobile Number in ADP is blank. No changes will be made to the mobile attribute." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserWorkMobileNumFormatted -ne $global:ADUserWorkMobileNum) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -mobile $global:ADPUserWorkMobileNumFormatted -Server kvc.org
            "UPDATING: Users Work Mobile phone $global:ADUserWorkMobileNum will be overwritten with value $global:ADPUserWorkMobileNumFormatted" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users mobile attribute value with the following data: $global:ADPUserWorkMobileNumFormatted Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
    }
    else {
        "NOCHANGE: The Users Work Mobile Phone number information in ADP already matches the AD objects attribute value: ADP Value = $global:ADPUserWorkMobileNumFormatted <==> AD Value = $global:ADUserWorkMobileNum" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }     
    #Process Users Facsimile Telephone Number       
    if ($global:ADPUserWorkFacsimileNumFormatted -eq '') {
        "BLANK: The Users Work Facsimile Number in ADP is blank. No changes will be made to the facsimileTelephoneNumber attribute." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        #Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Clear facsimileTelephoneNumber -Server kvc.org
    }
    elseif ($global:ADPUserWorkFacsimileNumFormatted -ne $global:ADUserWorkFacsimileNum) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Fax $global:ADPUserWorkFacsimileNumFormatted -Server kvc.org
            "UPDATING: Users Work Facsimile Number $global:ADUserWorkFacsimileNum will be overwritten with value $global:ADPUserWorkFacsimileNumFormatted" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users fax attribute value with the following data: $global:ADPUserWorkFacsimileNumFormatted Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }      
    }
    else {
        "NOCHANGE: The Users Work Facsimile number information in ADP already matches the AD objects attribute value: ADP Value = $global:ADPUserWorkFacsimileNumFormatted <==> AD Value = $global:ADUserWorkFacsimileNum" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users Work Street Address locale     
    if ($global:ADPUserStreetAddress -eq '') {
        "BLANK: The Users Work Street Address in ADP is blank. No changes will be made to the streetAddress attribute." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserStreetAddress -ne $global:ADUserActDirData.streetAddress) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -StreetAddress $global:ADPUserStreetAddress -Server kvc.org
            "UPDATING: Street $global:ADUserStreetAddress will be overwritten with value $global:ADPUserStreetAddress" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users streetAddress attribute value with the following data: $global:ADPUserStreetAddress Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }        
    }
    else {
        "NOCHANGE: The Users Office Street Address information in ADP already matches the AD objects attribute value: ADP Value = $global:ADPUserStreetAddress <==> AD Value = $global:ADUserStreetAddress" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users Work City locale
    if ($global:ADPUserCity -eq '') {
        "BLANK: The Users Work City locale information in ADP is blank. No changes will be made to the City attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserCity -ne $global:ADUserActDirData.City) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -City $global:ADPUserCity -Server kvc.org
            "UPDATING: City $global:ADUserCity will be overwritten with value $global:ADPUserCity" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users city attribute value with the following data: $global:ADPUserCity Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }        
    }
    else {
        "NOCHANGE: The Users Work City locale information in ADP already matches the AD objects City attribute value: ADP Value = $global:ADPUserCity <==> AD Value = $global:ADUserCity" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users Work State locale
    if ($global:ADPUserState -eq '') {
        "BLANK: The Users Work State locale information in ADP is blank. No changes will be made to the State attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserState -ne $global:ADUserActDirData.st) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -State $global:ADPUserState -Server kvc.org
            "UPDATING: State $global:ADUserState will be overwritten with value $global:ADPUserState" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users state attribute value with the following data: $global:ADPUserState Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }       
    }
    else {
        "NOCHANGE: The Users Work State locale information in ADP already matches the AD objects State attribute value: ADP Value = $global:ADPUserState <==> AD Value = $global:ADUserState" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users Work Postal Code locale
    if ($global:ADPUserPostalCode -eq '') {
        "BLANK: The Users Work Postal Code locale information in ADP is blank. No changes will be made to the postalCode attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    elseif ($global:ADPUserPostalCode -ne $global:ADUserActDirData.postalCode) {
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -PostalCode $global:ADPUserPostalCode -Server kvc.org
            "UPDATING: PostalCode $global:ADUserPostalCode will be overwritten with value $global:ADPUserPostalCode" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users postalCode attribute value with the following data: $global:ADPUserPostalCode Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }        
    }
    else {
        "NOCHANGE: The Users Office Postal Code locale information in ADP already matches the AD objects attribute value:  ADP Value = $global:ADPUserPostalCode <==> AD Value = $global:ADUserPostalCode" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
    #Process Users Reports To Manager  
    if ($global:ADPADUserReportsToManagerDistName -eq '') {
        "BLANK: The Users Report To Manager in ADP is blank. No changes will be made to the manager attribute value." | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }    
    elseif ($global:ADPADUserReportsToManagerDistName -ne $global:ADUserADManagerPulledFromAD.DistinguishedName) {
        $global:ADUserADManagerNamePFADDistName = $null
        $global:ADUserADManagerNamePFADDistName = $global:ADUserADManagerPulledFromAD.DistinguishedName
        try {
            Set-ADUser -Identity $global:ADUserActDirData.sAMAccountName -Manager $global:ADUserADManagerPulledFromAD.sAMAccountName -Server kvc.org
            "UPDATING: User's Manager $global:ADPADUserReportsToManagerDistName will be overwritten with value $global:ADUserADManagerNamePFADDistName" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
        catch {
            "ERROR: There was a problem updating the following user: $global:ADUserPrincipalName The script was unable to update the users manager attribute value with the following data: $global:ADPADUserReportsToManagerDistName Please review the SYSTEMERROR on the next line."  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
            "SYSTEMERROR: $_"  | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
        }
    }
    else {
        $global:ADUserADManagerNamePFADDistName = $global:ADUserADManagerPulledFromAD.DistinguishedName
        "NOCHANGE: The User's manager information in ADP already matches the AD objects attribute value: ADP Value = $global:ADUserADManagerNamePFADDistName <==> AD Value = $global:ADPADUserReportsToManagerDistName" | Out-File -FilePath $global:LogfileExportPathandName -NoClobber -Append
    }
}

I wouldn’t say I figured out my problem as I have a long way to go understanding the logic structure of everything in PowerShell universal but I’m pretty sure my issue was a scoping problem. I have since pivoted to using functions to create my modals and almost all the code is in the functions. It seems to be working though I still have to to and refine to fully understand what’s going to happen to the data during aa long script run. But after reading a lot about scopes on other peoples posts by @Jori @Mutiny1 @adam and a couple others. I did a complete re-work and things are working much better.
I’m not done and I’m sure I’m making mistakes but I thought I’d post for both my own memory issues and who knows.

function Set-ADPImportFunctionVariableGlobalTimestamp {
    #comment to commit checkpoint
    $session:ADPImportFunctionVariablelTimestamp = $null
    $session:ADPImportFunctionVariablelTimestamp = Get-Date -Format "yyyy-MM-dd-hh-mm-ss"
}
function Set-ADPUploadFileData {
    New-UDTypography -Text 'Use this simple form to submit ADP CSV Export Files' -Variant h3
    New-UDTypography -Text 'THE DATA IN THE DOCUMENT WILL MAKE PERMANENT CHANGES TO THE ACTIVE DIRECTORY' -Variant subtitle1 -Style @{ color = 'red' }
    New-UDTypography -Text 'PLEASE CONFIRM THE DATA IN THE FILE BEFORE SUBMITTING' -Variant subtitle1 -Style @{ color = 'red' }
    #Its behind
    New-UDUpload -Id 'UDUImportADPCSVtoAD' -Accept '.CSV' -OnUpload {
        $page:ADPUploadFileValidation = $null
        $page:ADPUploadPathValidation = $null
        $page:ADPCSVUploadBodyRawData = $null
        $page:ADPCSVUploadBodyRawData = $Body
        $page:ADPUploadFrmFileNameTimestamp = $null
        $page:ADPUploadFrmData = $null 
        $page:ADPUploadFrmJSONBytes = $null
        $page:ADPUploadFrmFileName = $null
        $page:ADPUploadFrmFolderPath = $null
        $page:ADPUploadFrmFPathPlusFName = $null
        $page:ADPUploadFrmFileNameTimestamp = $session:ADPImportFunctionVariablelTimestamp
        $page:ADPUploadFrmData = $page:ADPCSVUploadBodyRawData | ConvertFrom-Json 
        $page:ADPUploadFrmJSONBytes = [System.Convert]::FromBase64String($page:ADPUploadFrmData.Data)
        $page:ADPUploadFileValidation = $page:ADPUploadFrmData.Name
        $page:ADPUploadFrmFileName = $page:ADPUploadFrmData.Name
        $page:ADPUploadFrmFolderPath = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\ADPData"
        If (-not (Test-Path -Path $page:ADPUploadFrmFolderPath -ErrorAction SilentlyContinue)) {
            #Folder does not exist, create it
            New-Item -Path $page:ADPUploadFrmFolderPath -ItemType Directory -Force
        }
        $page:ADPUploadPathValidation = "$page:ADPUploadFrmFolderPath\$page:ADPUploadFrmFileNameTimestamp-$page:ADPUploadFrmFileName"
        $page:ADPUploadFrmFPathPlusFName = "$page:ADPUploadFrmFolderPath\$page:ADPUploadFrmFileNameTimestamp-$page:ADPUploadFrmFileName"
        [System.IO.File]::WriteAllBytes($page:ADPUploadFrmFPathPlusFName, $page:ADPUploadFrmJSONBytes)
    } -Text 'Upload ADP CSV File to Process'
}
function Set-ADPImportLogFile {
    #Null out log file variables
    $session:LogfileTimestamp = $null
    $session:LogfileExportPathandName = $null
    #set log file timestamp to global
    $session:LogfileTimestamp = $session:ADPImportFunctionVariablelTimestamp
    #set log file path
    $session:LogfileExportPathandName = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\ADPLogs\ADPSync-Log-$session:LogfileTimestamp.txt"
}
function Validate-ADPUploadFile {
    if ($page:ADPUploadFileValidation -like "*.csv") {
        #store uploaded csv data into variable for analysis
        $session:ADPUserCSVData = $null
        $session:ADPUserCSVData = Import-Csv -Path $page:ADPUploadFrmFPathPlusFName
        #Variable for measuring if file has records
        $session:ADPUserCSVDataMeasure = $null
        #array for submitted file compare variables
        $session:ADPCSVHeaderNamesObjCompareDif = @()
        #Array Headers that should be present in the submitted CSV
        $cache:ADPCSVHeaderNamesObjCompareRef = @()
        $cache:ADPCSVHeaderNamesObjCompareRef = @('Associate ID', 'File Number', 'Hire/Rehire Date', 'Home Department Code', 'Home Department Description', 'Job Title Description', 'Legal First Name', 'Legal Last Name', 'Location Description', 'Payroll Company Code', 'Personal Contact: Personal Mobile', 'Position ID', 'Position Status', 'Preferred or Chosen First Name', 'Professional Suffix Code', 'Pronouns', 'Reports To Associate ID', 'Reports To Name', 'Termination Date', 'Work Address: Address Line 1', 'Work Address: City', 'Work Address: State / Territory Code', 'Work Address: Zip / Postal Code', 'Work Contact: Work Email', 'Work Contact: Work Fax', 'Work Contact: Work Mobile', 'Work Contact: Work Phone', 'Worker Category Description')
        #null out results variable
        $session:ADPCSVHeaderNamesCompared = $null
        #measure the amount of records in file
        $session:ADPUserCSVDataMeasure = $session:ADPUserCSVData | Measure-Object
        #Compare header names and store
        $session:ADPCSVHeaderNamesObjCompareDif = ($session:ADPUserCSVData | Get-Member -MemberType NoteProperty -ErrorAction SilentlyContinue).Name
        #compare headers and store in variable
        try { 
            $session:ADPCSVHeaderNamesCompared = Compare-Object -ReferenceObject $cache:ADPCSVHeaderNamesObjCompareRef -DifferenceObject $session:ADPCSVHeaderNamesObjCompareDif -CaseSensitive
        }
        catch {
        }
        $cache:ADPCSVMisspelledHeaders = $null
        $cache:ADPCSVMissingHeaders = $null
        $cache:ADPCSVMisspelledHeaders = ($session:ADPCSVHeaderNamesCompared | Where-Object { $_.SideIndicator -eq "=>" }).InputObject
        $cache:ADPCSVMissingHeaders = ($session:ADPCSVHeaderNamesCompared | Where-Object { $_.SideIndicator -eq "<=" }).InputObject
        if ($session:ADPCSVHeaderNamesCompared.Count -gt 0) {
            Show-UDModal -Footer {
                New-UDButton -Text 'TRY AGAIN' -OnClick {
                    $page:ADPUploadPathValidation = $null
                    $page:ADPUploadFileValidation = $null
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -Content {
                #begin logging
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Logging started: $session:LogfileTimestamp" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Log File Location on kvchs-pshell01.kvc.org - $session:LogfileExportPathandName" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Uploaded CSV File Location on kvchs-pshell01.kvc.org - $page:ADPUploadPathValidation" -Force
                if ($cache:ADPCSVMisspelledHeaders.count -gt 0) {
                    Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: The file submiteed has some headers that are misspelled. Please correct the following header names: $cache:ADPCSVMisspelledHeaders" -Force
                    New-UDAlert -Severity 'error' -Content { New-UDTypography -Text "ERROR: The file submiteed has some headers that are misspelled. Please correct the following header names: $cache:ADPCSVMisspelledHeaders" } -Title "File Contains Misspelled Column Headers!"
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: The ADP CSV you submitted is missing the following Column Headers: $cache:ADPCSVMissingHeaders" -Force
                    New-UDAlert -Severity 'error' -Content { New-UDTypography -Text "ERROR: The ADP CSV you submitted is missing the following Column Headers: $cache:ADPCSVMissingHeaders" } -Title "File Has Missing Column Headers!"
                }
            } -Persistent
        }
        elseif ($session:ADPUserCSVDataMeasure.Count -eq 0) {
            Show-UDModal -Footer {
                New-UDButton -Text 'TRY AGAIN' -OnClick {
                    $page:ADPUploadPathValidation = $null
                    $page:ADPUploadFileValidation = $null
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -Content {
                #begin logging
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Logging started: $session:LogfileTimestamp" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Log File Location on kvchs-pshell01.kvc.org - $session:LogfileExportPathandName" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Uploaded CSV File Location on kvchs-pshell01.kvc.org - $page:ADPUploadPathValidation" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: The ADP CSV file submitted for import was analyzed and was found to have no users that could be processed." -Force
                New-UDTypography -Text 'You have submitted a CSV file that has no records in it, please choose a file with at least one user to process.'
            } -Persistent
        }
        elseif (($session:ADPUserCSVDataMeasure.count -gt 0) -and ($session:ADPUserCSVDataMeasure.count -lt 1001)) {
            New-UDFormValidationResult -Valid:$True
            #begin logging
            Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Logging started: $session:LogfileTimestamp" -Force
            Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Log File Location on kvchs-pshell01.kvc.org - $session:LogfileExportPathandName" -Force
            Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Uploaded CSV File Location on kvchs-pshell01.kvc.org - $page:ADPUploadPathValidation" -Force
        }
        elseif ($session:ADPUserCSVDataMeasure.count -gt 1000) {
            Show-UDModal -Footer {
                New-UDButton -Text 'TRY AGAIN' -OnClick {
                    $page:ADPUploadPathValidation = $null
                    $page:ADPUploadFileValidation = $null
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -Content {
                #begin logging
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Logging started: $session:LogfileTimestamp" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Log File Location on kvchs-pshell01.kvc.org - $session:LogfileExportPathandName" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Uploaded CSV File Location on kvchs-pshell01.kvc.org - $page:ADPUploadPathValidation" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: The ADP CSV file submitted for import was analyzed and was found to have $($session:ADPUserCSVDataMeasure.count) Users to be processed. This exceeds the allowable amount of 1000 total users per import." -Force
                New-UDTypography -Text 'You have submitted a CSV file that exceeds the maximum allowable objects to update at one time. Please reduce the amount of records you wish to update to 1000 or less and try again.'
            } -Persistent
        }
        else {
            Show-UDModal -Footer {
                New-UDButton -Text 'TRY AGAIN' -OnClick {
                    $page:ADPUploadPathValidation = $null
                    $page:ADPUploadFileValidation = $null
                    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
                    Hide-UDModal
                }
            } -Content {
                #begin logging
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Logging started: $session:LogfileTimestamp" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Log File Location on kvchs-pshell01.kvc.org - $session:LogfileExportPathandName" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Uploaded CSV File Location on kvchs-pshell01.kvc.org - $page:ADPUploadPathValidation" -Force
                Add-Content -Path $session:LogfileExportPathandName  -Value "ERROR: The ADP CSV file submitted for import was analyzed and though it passed all the validation checks, something went wrong. All the powershell errors for this session should be reported on the next line." -Force
                Add-Content -Path $session:LogfileExportPathandName  -Value "SYSTEMERROR: $Error" -Force
                New-UDTypography -Text 'You have submitted a CSV file that is unable to validate. Please confirm the format and values and try again.'
            } -Persistent
        }
    }
    else {
        New-UDFormValidationResult -ValidationError "Please upload a CSV file to continue."
        If (Test-Path -Path $page:ADPUploadPathValidation -ErrorAction SilentlyContinue) {
            Remove-Item -Path $page:ADPUploadPathValidation -Force -Exclude *.csv
        }
        $page:ADPUploadFileValidation = $null
        $page:ADPUploadPathValidation = $null
    }
}

function Submit-ADPUploadFile {
    Show-UDModal -Footer {
        New-UDButton -Id 'UDBTNADPProcessAnother' -OnClick {
            $page:ADPUploadPathValidation = $null
            $page:ADPUploadFileValidation = $null
            $session:ADPUserCSVData = $null
            $page:ADPUploadFrmFPathPlusFName = $null
            Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
            Hide-UDModal
        } -Text 'START OVER'
    } -Content {
        Add-Content -Path $session:LogfileExportPathandName -Value "INFO: ADP Import Process Started by User: $User" -Force
        Add-Content -Path $session:LogfileExportPathandName -Value "INFO: The ADP CSV file submitted for import passed all validation tests. The users submitted will be updated." -Force
        New-UDTypography -Text 'ADP Data is Now Importing' -Variant h3 -Style @{ color = 'green' }
        #null out Pre-Import Variables
        $page:CSVPreCompFileTimestamp = $null
        $session:CSVPreComparisonPathandName = $null
        #null out Post-Import Variables
        $page:CSVPostCompFileTimestamp = $null
        $session:CSVPostComparisonPathandName = $null
        #set Pre-Import path and file name info
        $page:CSVPreCompFileTimestamp = $session:ADPImportFunctionVariablelTimestamp
        $session:CSVPreComparisonPathandName = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\Pre-ADPtoADUserUpdateRecord\Pre-ProcessedADUserAttributeValues-$page:CSVPreCompFileTimestamp.csv"
        #set Post-Import path and file name info
        $page:CSVPostCompFileTimestamp = $session:ADPImportFunctionVariablelTimestamp
        $session:CSVPostComparisonPathandName = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\Post-ADPtoADUserUpdateRecord\Post-ProcessedADUserAttributeValues-$page:CSVPostCompFileTimestamp.csv"
        $page:ADPNumberOfUsersSubmitted = 0
        $page:ADPNumberOfUsersSubmitted = $session:ADPUserCSVDataMeasure.count
        $page:ADPNumberOfCurrentUserBeingProcessed = 0
        New-UDDynamic -Id 'UDDYADPImportProgressStatus' -Content {
            $page:ADPImportProgressPercent = 0
            $page:ADPImportProgressPercent = ($page:ADPNumberOfCurrentUserBeingProcessed / $page:ADPNumberOfUsersSubmitted) * 100
            $page:ADPImportProgressPercent = [math]::Round($page:ADPImportProgressPercent)
            $page:ADPImportProgressPercentCosmetic = $null
            $page:ADPImportProgressPercentCosmetic = ($page:ADPNumberOfCurrentUserBeingProcessed / $page:ADPNumberOfUsersSubmitted).tostring("P")
            New-UDTypography -Content { "The $page:ADPNumberOfUsersSubmitted users you submitted for update are now processing." } -Variant h4
            New-UDProgress -PercentComplete $page:ADPImportProgressPercent
            New-UDTypography -Content { "Percent Complete: $page:ADPImportProgressPercentCosmetic" } -Variant h4
        }
        New-UDDynamic -Id 'UDDYADPImportForEach' -Content {
            foreach ($session:ADPUserCSV in $session:ADPUserCSVData) {
                #reset all variables used to hold data from ADP CSV
                #Null variables used to hold csv values
                $session:ADPUserAssocID = $null
                $session:ADPUserJobTitle = $null
                $session:ADPUserFileNumber = $null
                $session:ADPUserOffice = $null
                $session:ADPUserDepartment4Digit = $null
                $session:ADPUserDepartmentDescript = $null
                $session:ADPUserReportToManager = $null
                $session:ADPUserWorkOfficeNum = $null
                $session:ADPUserWorkMobileNum = $null
                $session:ADPUserWorkFacsimileNum = $null
                $session:ADPUserStreetAddress = $null
                $session:ADPUserCity = $null
                $session:ADPUserState = $null
                $session:ADPUserPostalCode = $null
                $session:ADPUserHireDate = $null
                $session:ADPUserTermDate = $null

                #immediately populate those attributes with data from csv
                $session:ADPUserAssocID = $session:ADPUserCSV."Associate ID"
                $session:ADPUserJobTitle = $session:ADPUserCSV."Job Title Description"
                $session:ADPUserFileNumber = $session:ADPUserCSV."File Number"
                $session:ADPUserOffice = $session:ADPUserCSV."Location Description"
                $session:ADPUserDepartment4Digit = $session:ADPUserCSV."Home Department Code"
                $session:ADPUserDepartmentDescript = $session:ADPUserCSV."Home Department Description"
                $session:ADPUserReportToManager = $session:ADPUserCSV."Reports To Associate ID"
                $session:ADPUserWorkOfficeNum = $session:ADPUserCSV."Work Contact: Work Phone"
                $session:ADPUserWorkMobileNum = $session:ADPUserCSV."Work Contact: Work Mobile"
                $session:ADPUserWorkFacsimileNum = $session:ADPUserCSV."Work Contact: Work Fax"
                $session:ADPUserStreetAddress = $session:ADPUserCSV."Work Address: Address Line 1"
                $session:ADPUserCity = $session:ADPUserCSV."Work Address: City"
                $session:ADPUserState = $session:ADPUserCSV."Work Address: State / Territory Code"
                $session:ADPUserPostalCode = $session:ADPUserCSV."Work Address: Zip / Postal Code"
                $session:ADPUserHireDate = $session:ADPUserCSV."Hire/Rehire Date"
                $session:ADPUserTermDate = $session:ADPUserCSV."Termination Date"
                #format FileNumber and Dept Code
                if (($session:ADPUserDepartment4Digit).tostring().length -gt 4) { $session:ADPUserDepartment4Digit = $session:ADPUserDepartment4Digit -replace '^0+(?=[^.])', '' }
                if (($session:ADPUserFileNumber).tostring().length -gt 5) { $session:ADPUserFileNumber = $session:ADPUserFileNumber -replace '^0+(?=[^.])', '' }

                #reset all variables used to hold data Users current AD Data
                #Null variable that holds user to process
                $session:ADUserActDirData = $null
                #null Attributes for handling a users manager setting
                $session:ADPADUserReportsToManagerDistName = $null
                #Null sub-variables that holds user specific sub-variables
                $session:ADUserEmployeeID = $null
                $session:ADUserPrincipalName = $null
                $session:ADUserAccountExpirationDate = $null
                $session:ADUserJobTitle = $null
                $session:ADUserDepartmentDescript = $null
                $session:ADUserPDON = $null
                $session:ADUserWorkOfficeNum = $null
                $session:ADUserWorkMobileNum = $null
                $session:ADUserWorkFacsimileNum = $null
                $session:ADUserStreetAddress = $null
                $session:ADUserCity = $null
                $session:ADUserState = $null
                $session:ADUserPostalCode = $null
                #extensionAttribute5 is the users Department Description; until the dynamic groups are updated this has to stay numeric
                $session:ADUserExtAttrib5 = $null
                #extensionAttribute6 is the users ADP File Number
                $session:ADUserExtAttrib6 = $null
                #extensionAttribute7 is the users Hire Date
                $session:ADUserExtAttrib7 = $null
                #extensionAttribute8 is the users Termination Date
                $session:ADUserExtAttrib8 = $null
                #extensionAttribute15 is the users Telephone Number attribute but formatted to be used in the email signature
                $session:ADUserExtAttrib15 = $null
                #Variable specifically to get and hold the users manager from the AD by employeeID
                $session:ADUserADManagerPulledFromAD = $null

                #immediately set those variables with the currently processing users AD attribute values
                $session:ADUserActDirData = Get-ADUser -LDAPFilter “(employeeID=$session:ADPUserAssocID)” -Properties sAMAccountName, employeeID, userPrincipalName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 -Server kvc.org | Select-Object -Property sAMAccountName, userPrincipalName, employeeID, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15
                $session:ADPADUserReportsToManagerDistName = $session:ADUserActDirData.manager
                $session:ADUserEmployeeID = $session:ADUserActDirData.employeeID
                $session:ADUserPrincipalName = $session:ADUserActDirData.userPrincipalName
                $session:ADUserAccountExpirationDate = $session:ADUserActDirData.accountExpirationDate
                $session:ADUserJobTitle = $session:ADUserActDirData.Title
                $session:ADUserDepartmentDescript = $session:ADUserActDirData.Department
                $session:ADUserPDON = $session:ADUserActDirData.physicalDeliveryOfficeName
                $session:ADUserWorkOfficeNum = $session:ADUserActDirData.telephoneNumber
                $session:ADUserWorkMobileNum = $session:ADUserActDirData.mobile
                $session:ADUserWorkFacsimileNum = $session:ADUserActDirData.facsimileTelephoneNumber
                $session:ADUserStreetAddress = $session:ADUserActDirData.StreetAddress
                $session:ADUserCity = $session:ADUserActDirData.city
                $session:ADUserState = $session:ADUserActDirData.st
                $session:ADUserPostalCode = $session:ADUserActDirData.postalCode
                $session:ADUserExtAttrib5 = $session:ADUserActDirData.extensionAttribute5
                $session:ADUserExtAttrib6 = $session:ADUserActDirData.extensionAttribute6
                $session:ADUserExtAttrib7 = $session:ADUserActDirData.extensionAttribute7
                $session:ADUserExtAttrib8 = $session:ADUserActDirData.extensionAttribute8
                $session:ADUserExtAttrib15 = $session:ADUserActDirData.extensionAttribute15

                try {
                    $session:ADUserADManagerPulledFromAD = Get-ADUser -LDAPFilter “(employeeID=$session:ADPUserReportToManager)” -Properties sAMAccountName, userPrincipalName, DistinguishedName | Select-Object sAMAccountName, userPrincipalName, DistinguishedName
                }
                catch {
                    Add-Content -Path $session:LogfileExportPathandName -Value "PROCESSING: $session:ADUserPrincipalName has no manager set in the AD." -Force
                }

                #Clear variables used to hold the phone numbers from ADP then properly format them
                #there attributes that hold the non formatted numbers are in the other functions
                #Null variables for phone number fomatting
                $session:ADPUserWorkOfficeNumFormatted = $null
                $session:ADPUserWorkMobileNumFormatted = $null
                $session:ADPUserWorkFacsimileNumFormatted = $null
                $session:ADPUserWorkOfficeNumFormattedForSignature = $null
                #working format command but a bit complicated
                $session:ADPUserWorkOfficeNumFormatted = $session:ADPUserWorkOfficeNum -replace "[^0-9]", "" -replace "^1(\d{10})$", '$1' -replace "(\d{3})(\d{3})(\d{4})", '+1$1$2$3'
                $session:ADPUserWorkMobileNumFormatted = $session:ADPUserWorkMobileNum -replace "[^0-9]", "" -replace "^1(\d{10})$", '$1' -replace "(\d{3})(\d{3})(\d{4})", '$1-$2-$3'
                $session:ADPUserWorkFacsimileNumFormatted = $session:ADPUserWorkFacsimileNum -replace "[^0-9]", "" -replace "^1(\d{10})$", '$1' -replace "(\d{3})(\d{3})(\d{4})", '$1-$2-$3'
                $session:ADPUserWorkOfficeNumFormattedForSignature = $session:ADPUserWorkOfficeNum -replace "[^0-9]", "" -replace "^1(\d{10})$", '$1' -replace "(\d{3})(\d{3})(\d{4})", '$1-$2-$3'
                #write users AD values to a CSV before the change
                try {
                    #Build a Pre Import User list with attrib values CSV doc for the compare
                    Get-ADUser -LDAPFilter “(employeeID=$session:ADPUserAssocID)” -Properties sAMAccountName, employeeID, userPrincipalName, displayName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 | Select-Object sAMAccountName, employeeID, userPrincipalName, displayName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 | Export-Csv -Path $session:CSVPreComparisonPathandName -NoTypeInformation -NoClobber -Append
                }
                catch {
                    Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem polling the following users Pre-Update Attributes: $session:ADUserPrincipalName The error will be logged. Please review the SYSTEMERROR on the next line." -Force
                    Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                }
                #commit all the data that is detected to need an update to AD unless they are empty
                Add-Content -Path $session:LogfileExportPathandName -Value "PROCESSING: $session:ADUserPrincipalName ..." -Force
                #Process Users Job Title
if ($session:ADPUserJobTitle -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Job Title in ADP is blank. No changes will be made to the user's Job Title attribute value." -Force
                }
                elseif ($session:ADPUserJobTitle -ne $session:ADUserActDirData.title) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -Title $session:ADPUserJobTitle -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: Title $session:ADUserJobTitle will be overwritten with value $session:ADPUserJobTitle" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users title attribute value with the following data: $session:ADPUserJobTitle Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users ADP Job Title information in ADP already matches the AD objects Title attribute value: ADP Value = $session:ADPUserJobTitle <==> AD Value = $session:ADUserJobTitle" -Force
                }
                #Process Users File Number
                if ($session:ADPUserFileNumber -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users File Number in ADP is blank. No changes will be made to the user's File Number-(extensionAttribute6) attribute value." -Force
                }
                elseif ($session:ADPUserFileNumber -ne $session:ADUserActDirData.extensionAttribute6) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -Replace @{"extensionAttribute6" = $session:ADPUserFileNumber } -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: File Number-(extensionAttribute6) $session:ADUserExtAttrib6 will be overwritten with value $session:ADPUserFileNumber" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users extensionAttribute6 attribute value with the following data: $session:ADPUserFileNumber Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }     
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users ADP File Number-(extensionAttribute6) information in ADP already matches the AD objects File Number-(extensionAttribute6) attribute value: ADP Value = $session:ADPUserFileNumber <==> AD Value = $session:ADUserExtAttrib6" -Force
                }
       
                #Process Users 4 Digit Department Code
                if ($session:ADPUserDepartment4Digit -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users 4-Digit Department Code in ADP is blank. No changes will be made to the 4-Digit Department Code-(extensionAttribute5) attribute value." -Force
                }
                elseif ($session:ADPUserDepartment4Digit -ne $session:ADUserActDirData.extensionAttribute5) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -Replace @{"extensionAttribute5" = $session:ADPUserDepartment4Digit } -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: 4-Digit Department Code-(extensionAttribute5) $session:ADUserExtAttrib5 will be overwritten with value $session:ADPUserDepartment4Digit" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users extensionAttribute5 attribute value with the following data: $session:ADPUserDepartment4Digit Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users 4-Digit Department Code-(extensionAttribute5) information in ADP already matches the AD objects 4-Digit Department Code-(extensionAttribute5) attribute value: ADP Value = $session:ADPUserDepartment4Digit <==> AD Value = $session:ADUserExtAttrib5" -Force
                }
                #Process Users Department Description
                if ($session:ADPUserDepartmentDescript -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Department Name in ADP is blank. No changes will be made to the Department attribute value." -Force
                }   
                elseif ($session:ADPUserDepartmentDescript -ne $session:ADUserActDirData.department) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -Department $session:ADPUserDepartmentDescript -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: Department $session:ADUserDepartmentDescript will be overwritten with value $session:ADPUserDepartmentDescript" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users department attribute value with the following data: $session:ADPUserDepartmentDescript Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Department Name information in ADP already matches the AD objects Department attribute value: ADP Value = $session:ADPUserDepartmentDescript <==> AD Value = $session:ADUserDepartmentDescript" -Force
                }
                #Process Users HireDate
                if ($session:ADPUserHireDate -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Hire Date in ADP is blank. No changes will be made to the Hire Date-(extensionAttribute7) attribute value." -Force
                }    
                elseif ($session:ADPUserHireDate -ne $session:ADUserActDirData.extensionAttribute7) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -Replace @{"extensionAttribute7" = $session:ADPUserHireDate } -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: HireDate $session:ADUserExtAttrib7 will be overwritten with value $session:ADPUserHireDate" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users Hire Date-(extensionAttribute7) attribute value with the following data: $session:ADPUserHireDate Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Hire Date-(extensionAttribute7) information in ADP already matches the AD objects Hire Date-(extensionAttribute7) attribute value: ADP Value = $session:ADPUserHireDate <==> AD Value = $session:ADUserExtAttrib7" -Force
                }
                #Process Users Termination Date
                if ($session:ADPUserTermDate -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Term Date in ADP is blank. No changes will be made to the Term Date-(extensionAttribute8) attribute value." -Force
                }
                elseif ($session:ADPUserTermDate -ne $session:ADUserActDirData.extensionAttribute8) {
                    #Declare Variable for PArseExact DateTime MM/DD/YYYY
                    $session:ADUserUpdateAccountExpirDateFormat = "MM/dd/yyyy"
                    $session:ADUserAccountExpirationDateFormatted = $null
                    $session:ADUserAccountExpirationDateFormatted = [datetime]::ParseExact($session:ADPUserTermDate, "M/dd/yyyy", $null).ToString($session:ADUserUpdateAccountExpirDateFormat)
                    #Now that the Termination date from ADP has been formatted, set the both Term Date attribs for user
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -Replace @{"extensionAttribute8" = $session:ADPUserTermDate } -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: The Users Employment Termination Date-(extensionAttribue8) $session:ADUserExtAttrib8 will be overwritten with value $session:ADPUserTermDate" -Force
                        Set-ADAccountExpiration -Identity $session:ADUserActDirData.sAMAccountName -DateTime $session:ADUserAccountExpirationDateFormatted -Confirm:$False -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: The Users Employment Termination Date-(accountExpirationDate) $session:ADUserAccountExpirationDate will be overwritten with value $session:ADPUserTermDate" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users Termination Date-(extensionAttribue8) and Termination Date-(accountExpirationDate) attribute value with the following data: $session:ADPUserTermDate Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Employment Term Date-(extensionAttribute8) information in ADP already matches the AD objects Term Date-(extensionAttribute8) attribute value:  ADP Value = $session:ADPUserTermDate <==> AD Value = $session:ADUserExtAttrib8" -Force
                }
                #Process Users Office Name
                if ($session:ADPUserOffice -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Office Name in ADP is blank. No changes will be made to the physicalDeliveryOfficeName attribute value." -Force
                }        
                elseif ($session:ADPUserOffice -ne $session:ADUserActDirData.physicalDeliveryOfficeName) {
                    try {
                        Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: Currently the script does not update the Office Description value." -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users physicalDeliveryOfficeName attribute value with the following data: $session:ADPUserOffice Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }        
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Office Name information in ADP already matches the AD objects physicalDeliveryOfficeName attribute value: ADP Value = $session:ADPUserOffice <==> AD Value = $session:ADUserPDON" -Force
                }    
                #Process Users Work Telephone Number        
                if ($session:ADPUserWorkOfficeNumFormatted -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Work Office Number in ADP is blank. No changes will be made to the telephoneNumber or extensionAttribute15 attribute values." -Force
                }
                elseif ($session:ADPUserWorkOfficeNumFormatted -ne $session:ADUserWorkOfficeNum) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -OfficePhone $session:ADPUserWorkOfficeNumFormatted -Replace @{"extensionAttribute15" = $session:ADPUserWorkOfficeNumFormattedForSignature } -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: Work phone $session:ADUserWorkOfficeNum will be overwritten with value $session:ADPUserWorkOfficeNumFormatted" -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: extensionAttribute15 $session:ADUserExtAttrib15 will be overwritten with value $session:ADPUserWorkOfficeNumFormattedForSignature" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users telephoneNumber and extensionAttribute15 attribute value with the following data: $session:ADPUserWorkOfficeNumFormatted and $session:ADPUserWorkOfficeNumFormattedForSignature Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }        
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Work Office Number information in ADP already matches the AD objects telephoneNumber attribute value: ADP Value = $session:ADPUserWorkOfficeNumFormatted <==> AD Value = $session:ADUserWorkOfficeNum" -Force
                }     
                #Process Users Work Mobile Number      
                if ($session:ADPUserWorkMobileNumFormatted -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Work Mobile Number in ADP is blank. No changes will be made to the mobile attribute." -Force
                }
                elseif ($session:ADPUserWorkMobileNumFormatted -ne $session:ADUserWorkMobileNum) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -mobile $session:ADPUserWorkMobileNumFormatted -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: Users Work Mobile phone $session:ADUserWorkMobileNum will be overwritten with value $session:ADPUserWorkMobileNumFormatted" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users mobile attribute value with the following data: $session:ADPUserWorkMobileNumFormatted Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Work Mobile Phone number information in ADP already matches the AD objects attribute value: ADP Value = $session:ADPUserWorkMobileNumFormatted <==> AD Value = $session:ADUserWorkMobileNum" -Force
                }     
                #Process Users Facsimile Telephone Number       
                if ($session:ADPUserWorkFacsimileNumFormatted -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Work Facsimile Number in ADP is blank. No changes will be made to the facsimileTelephoneNumber attribute." -Force
                }
                elseif ($session:ADPUserWorkFacsimileNumFormatted -ne $session:ADUserWorkFacsimileNum) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -Fax $session:ADPUserWorkFacsimileNumFormatted -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: Users Work Facsimile Number $session:ADUserWorkFacsimileNum will be overwritten with value $session:ADPUserWorkFacsimileNumFormatted" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users fax attribute value with the following data: $session:ADPUserWorkFacsimileNumFormatted Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }      
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Work Facsimile number information in ADP already matches the AD objects attribute value: ADP Value = $session:ADPUserWorkFacsimileNumFormatted <==> AD Value = $session:ADUserWorkFacsimileNum" -Force
                }
                #Process Users Work Street Address locale     
                if ($session:ADPUserStreetAddress -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Work Street Address in ADP is blank. No changes will be made to the streetAddress attribute." -Force
                }
                elseif ($session:ADPUserStreetAddress -ne $session:ADUserActDirData.streetAddress) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -StreetAddress $session:ADPUserStreetAddress -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: Street $session:ADUserStreetAddress will be overwritten with value $session:ADPUserStreetAddress" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users streetAddress attribute value with the following data: $session:ADPUserStreetAddress Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }        
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Office Street Address information in ADP already matches the AD objects attribute value: ADP Value = $session:ADPUserStreetAddress <==> AD Value = $session:ADUserStreetAddress" -Force
                }
                #Process Users Work City locale
                if ($session:ADPUserCity -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Work City locale information in ADP is blank. No changes will be made to the City attribute value." -Force
                }
                elseif ($session:ADPUserCity -ne $session:ADUserActDirData.City) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -City $session:ADPUserCity -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: City $session:ADUserCity will be overwritten with value $session:ADPUserCity" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users city attribute value with the following data: $session:ADPUserCity Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }        
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Work City locale information in ADP already matches the AD objects City attribute value: ADP Value = $session:ADPUserCity <==> AD Value = $session:ADUserCity" -Force
                }
                #Process Users Work State locale
                if ($session:ADPUserState -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Work State locale information in ADP is blank. No changes will be made to the State attribute value." -Force
                }
                elseif ($session:ADPUserState -ne $session:ADUserActDirData.st) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -State $session:ADPUserState -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: State $session:ADUserState will be overwritten with value $session:ADPUserState" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users state attribute value with the following data: $session:ADPUserState Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }       
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Work State locale information in ADP already matches the AD objects State attribute value: ADP Value = $session:ADPUserState <==> AD Value = $session:ADUserState" -Force
                }
                #Process Users Work Postal Code locale
                if ($session:ADPUserPostalCode -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Work Postal Code locale information in ADP is blank. No changes will be made to the postalCode attribute value." -Force
                }
                elseif ($session:ADPUserPostalCode -ne $session:ADUserActDirData.postalCode) {
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -PostalCode $session:ADPUserPostalCode -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: PostalCode $session:ADUserPostalCode will be overwritten with value $session:ADPUserPostalCode" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users postalCode attribute value with the following data: $session:ADPUserPostalCode Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }        
                }
                else {
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The Users Office Postal Code locale information in ADP already matches the AD objects attribute value:  ADP Value = $session:ADPUserPostalCode <==> AD Value = $session:ADUserPostalCode" -Force
                }
                #Process Users Reports To Manager  
                if ($session:ADPADUserReportsToManagerDistName -eq '') {
                    Add-Content -Path $session:LogfileExportPathandName -Value "BLANK: The Users Report To Manager in ADP is blank. No changes will be made to the manager attribute value." -Force
                }    
                elseif ($session:ADPADUserReportsToManagerDistName -ne $session:ADUserADManagerPulledFromAD.DistinguishedName) {
                    $session:ADUserADManagerNamePFADDistName = $null
                    $session:ADUserADManagerNamePFADDistName = $session:ADUserADManagerPulledFromAD.DistinguishedName
                    try {
                        Set-ADUser -Identity $session:ADUserActDirData.sAMAccountName -Manager $session:ADUserADManagerPulledFromAD.sAMAccountName -Server kvc.org
                        Add-Content -Path $session:LogfileExportPathandName -Value "UPDATING: User's Manager $session:ADPADUserReportsToManagerDistName will be overwritten with value $session:ADUserADManagerNamePFADDistName" -Force
                    }
                    catch {
                        Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem updating the following user: $session:ADUserPrincipalName The script was unable to update the users manager attribute value with the following data: $session:ADPADUserReportsToManagerDistName Please review the SYSTEMERROR on the next line." -Force
                        Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                    }
                }
                else {
                    $session:ADUserADManagerNamePFADDistName = $session:ADUserADManagerPulledFromAD.DistinguishedName
                    Add-Content -Path $session:LogfileExportPathandName -Value "NOCHANGE: The User's manager information in ADP already matches the AD objects attribute value: ADP Value = $session:ADUserADManagerNamePFADDistName <==> AD Value = $session:ADPADUserReportsToManagerDistName" -Force
                }
                #write users AD values to a CSV after the change
                try {
                    #Build Post Import Import User list with attrib values CSV doc for the compare
                    Get-ADUser -LDAPFilter “(employeeID=$session:ADPUserAssocID)” -Properties sAMAccountName, employeeID, userPrincipalName, displayName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 | Select-Object sAMAccountName, employeeID, userPrincipalName, displayName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 | Sort-Object -Property userPrincipalName | Export-Csv -Path $session:CSVPostComparisonPathandName -NoTypeInformation -NoClobber -Append
                }
                catch {
                    Add-Content -Path $session:LogfileExportPathandName -Value "ERROR: There was a problem polling the following users Post-Update Attributes: $session:ADUserPrincipalName The error will be logged. Please review the SYSTEMERROR on the next line." -Force
                    Add-Content -Path $session:LogfileExportPathandName -Value "SYSTEMERROR: $_" -Force
                }
                $page:ADPNumberOfCurrentUserBeingProcessed++
                Sync-UDElement -Id 'UDDYADPImportProgressStatus'
            }
#null out Post-Import Variables
            $page:CSVCompareResultFileTimestamp = $null
            $page:CSVCompareResultsPath = $null
            $session:CSVCompareResultsPathandNameSuccess = $null
            $page:CSVCompareResultsPathandNameFailure = $null
            #set Pre-Import path and file name info
            $page:CSVCompareResultFileTimestamp = $session:ADPImportFunctionVariablelTimestamp
            $page:CSVCompareResultsPath = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\ADPADChangeComparisonResults"
            $session:CSVCompareResultsPathandNameSuccess = "$page:CSVCompareResultsPath\ProcessedADUserAttributeValuesCompared-$page:CSVCompareResultFileTimestamp.csv"
            $page:CSVCompareResultsPathandNameFailure = "$page:CSVCompareResultsPath\ProcessedADUserAttributeValuesCompared-$page:CSVCompareResultFileTimestamp-NODIFFERENCES-FILEBLANK.csv"
            #null out comparison variables
            $CSVPreRefValCompPostDifVals = @()
            $page:CSVCompareResultsPSOValues = $null
            $CSVArrayOfCompareResults = @()
            $page:CSVPreRecordIndexValue = 0
            $page:CSVPostRecordIndexValue = 0
            $page:ImportEmployeeTitleChange = $null
            $page:ImportEmployeeDepartmentChange = $null
            $page:ImportEmployeephysDelivOffNameChange = $null
            $page:ImportEmployeeTelephoneNumChange = $null
            $page:ImportEmployeeMobileNumChange = $null
            $page:ImportEmployeeFaxNumChange = $null
            $page:ImportEmployeeStreetAddrChange = $null
            $page:ImportEmployeeCityChange = $null
            $page:ImportEmployeeStateChange = $null
            $page:ImportEmployeePostalCodeChange = $null
            $page:ImportEmployeeManagerChange = $null
            $page:ImportEmployeeAccountExpirationChange = $null
            $page:ImportEmployeeextAttrib5Change = $null
            $page:ImportEmployeeextAttrib6Change = $null
            $page:ImportEmployeeextAttrib7Change = $null
            $page:ImportEmployeeextAttrib8Change = $null
            $page:ImportEmployeeextAttrib15Change = $null
            #Pre and Post value comparison code
            $CSVCompareResult = $null
            $CSVPreComparisonFileImport = $null
            $CSVPostComparisonFileImport = $null
            $CSVPreComparisonFileImport = Import-Csv -Path $session:CSVPreComparisonPathandName
            $CSVPostComparisonFileImport = Import-Csv -Path $session:CSVPostComparisonPathandName

            $CSVPreRefValCompPostDifVals = Compare-Object -ReferenceObject @($CSVPreComparisonFileImport | Select-Object) -DifferenceObject @($CSVPostComparisonFileImport | Select-Object) -Property employeeID, userPrincipalName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 -CaseSensitive -PassThru | Where-Object { $_.SideIndicator -eq "=>" }

            Foreach ($CSVCompareResult in $CSVPreRefValCompPostDifVals) {
                $page:CSVPreRecordIndexValue = [Array]::IndexOf($CSVPreComparisonFileImport.employeeID, $CSVCompareResult.employeeID)
                $page:CSVPostRecordIndexValue = [Array]::IndexOf($CSVPostComparisonFileImport.employeeID, $CSVCompareResult.employeeID)
                $page:ImportEmployeeTitleChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].title) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].title)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].title } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].title + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].title }
                $page:ImportEmployeeDepartmentChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].department) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].department)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].department } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].department + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].department }
                $page:ImportEmployeephysDelivOffNameChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].physicalDeliveryOfficeName) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].physicalDeliveryOfficeName)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].physicalDeliveryOfficeName } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].physicalDeliveryOfficeName + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].physicalDeliveryOfficeName }
                $page:ImportEmployeeTelephoneNumChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].telephoneNumber) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].telephoneNumber)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].telephoneNumber } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].telephoneNumber + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].telephoneNumber }
                $page:ImportEmployeeMobileNumChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].mobile) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].mobile)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].mobile } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].mobile + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].mobile }
                $page:ImportEmployeeFaxNumChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].facsimileTelephoneNumber) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].facsimileTelephoneNumber)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].facsimileTelephoneNumber } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].facsimileTelephoneNumber + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].facsimileTelephoneNumber }
                $page:ImportEmployeeStreetAddrChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].streetAddress) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].streetAddress)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].streetAddress } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].streetAddress + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].streetAddress }
                $page:ImportEmployeeCityChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].city) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].city)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].city } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].city + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].city }
                $page:ImportEmployeeStateChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].st) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].st)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].st } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].st + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].st }
                $page:ImportEmployeePostalCodeChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].postalCode) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].postalCode)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].postalCode } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].postalCode + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].postalCode }
                $page:ImportEmployeeManagerChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].manager) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].manager)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].manager } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].manager + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].manager }
                $page:ImportEmployeeAccountExpirationChange = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].accountExpirationDate) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].accountExpirationDate)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].accountExpirationDate } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].accountExpirationDate + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].accountExpirationDate }
                $page:ImportEmployeeextAttrib5Change = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute5) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute5)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute5 } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute5 + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute5 }
                $page:ImportEmployeeextAttrib6Change = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute6) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute6)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute6 } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute6 + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute6 }
                $page:ImportEmployeeextAttrib7Change = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute7) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute7)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute7 } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute7 + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute7 }
                $page:ImportEmployeeextAttrib8Change = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute8) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute8)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute8 } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute8 + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute8 }
                $page:ImportEmployeeextAttrib15Change = if (($CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute15) -eq ($CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute15)) { "Value Did Not Change: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute15 } else { "Previous Value: " + $CSVPreComparisonFileImport[$page:CSVPreRecordIndexValue].extensionAttribute15 + " | Updated Value: " + $CSVPostComparisonFileImport[$page:CSVPostRecordIndexValue].extensionAttribute15 }

                $page:CSVCompareResultsPSOValues = [pscustomobject][ordered] @{
                    employeeID                 = $CSVCompareResult.employeeID
                    userPrincipalName          = $CSVCompareResult.userPrincipalName
                    title                      = $page:ImportEmployeeTitleChange
                    department                 = $page:ImportEmployeeDepartmentChange
                    physicalDeliveryOfficeName = $page:ImportEmployeephysDelivOffNameChange
                    telephonenumber            = $page:ImportEmployeeTelephoneNumChange
                    mobile                     = $page:ImportEmployeeMobileNumChange
                    facsimileTelephoneNumber   = $page:ImportEmployeeFaxNumChange
                    streetAddress              = $page:ImportEmployeeStreetAddrChange
                    city                       = $page:ImportEmployeeCityChange
                    st                         = $page:ImportEmployeeStateChange
                    postalCode                 = $page:ImportEmployeePostalCodeChange
                    manager                    = $page:ImportEmployeeManagerChange
                    accountExpirationDate      = $page:ImportEmployeeAccountExpirationChange
                    extensionAttribute5        = $page:ImportEmployeeextAttrib5Change
                    extensionAttribute6        = $page:ImportEmployeeextAttrib6Change
                    extensionAttribute7        = $page:ImportEmployeeextAttrib7Change
                    extensionAttribute8        = $page:ImportEmployeeextAttrib8Change
                    extensionAttribute15       = $page:ImportEmployeeextAttrib15Change
                }
                $CSVArrayOfCompareResults += $page:CSVCompareResultsPSOValues
            }
            Add-Content -Path $session:LogfileExportPathandName -Value "INFO: The attribute values for the uploaded list of users has been processed." -Force
            if (($CSVArrayOfCompareResults | Sort-Object userPrincipalName | Select-Object * -Unique).count -gt 0) {
                $CSVArrayOfCompareResults | Select-Object employeeID, userPrincipalName, title, department, physicalDeliveryOfficeName, telephoneNumber, mobile, facsimileTelephoneNumber, streetAddress, city, st, postalCode, manager, accountExpirationDate, extensionAttribute5, extensionAttribute6, extensionAttribute7, extensionAttribute8, extensionAttribute15 | Export-Csv -Path $session:CSVCompareResultsPathandNameSuccess -Append -NoClobber -NoTypeInformation
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: The attribute values of the submitted users where logged before being updated in file: $session:CSVPreComparisonPathandName" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: The attribute values of the submitted users where logged after being updated in file: $session:CSVPostComparisonPathandName" -Force
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: The results from comparing the attribute values before and after import are available in file: $session:CSVCompareResultsPathandNameSuccess" -Force
            }
            else {
                Add-Content -Path $session:LogfileExportPathandName -Value "INFO: After comparing the submitted users attribute values, NO changes were detected. A place holder file was created and is located in the log folder: $page:CSVCompareResultsPath" -Force
                Add-Content -Path $page:CSVCompareResultsPathandNameFailure -Value "This file was created as a placeholder. No differences where detected." -Force
            }
$LogFileForEmail = $null
            $PreFileForEmail = $null
            $PostFileForEmail = $null
            $CompFileForEmail = $null
            $LogFileForEmail = $session:LogfileExportPathandName
            $PreFileForEmail = $session:CSVPreComparisonPathandName
            $PostFileForEmail = $session:CSVPostComparisonPathandName
            $CompFileForEmail = $session:CSVCompareResultsPathandNameSuccess
            #Connect to Microsoft Graph Module
            Connect-MicrosoftGraphAppAuth
            #Null out email variables
            $cache:ADPIRSender = 'ADPImportReport@kvc.org'
            $cache:ADPIRRecipient = 'aruss@kvc.org'
            $ADPImportLogFileEmailAttachment = $null
            $ADPImportLogFileEmailAttachment = [Convert]::ToBase64String([IO.File]::ReadAllBytes($LogFileForEmail))
            $ADPImportPreFileEmailAttachment = $null
            $ADPImportPreFileEmailAttachment = [Convert]::ToBase64String([IO.File]::ReadAllBytes($PreFileForEmail))
            $ADPImportPostFileEmailAttachment = $null
            $ADPImportPostFileEmailAttachment = [Convert]::ToBase64String([IO.File]::ReadAllBytes($PostFileForEmail))
            $ADPImportCompFileEmailAttachment = $null
            $ADPImportCompFileEmailAttachment = [Convert]::ToBase64String([IO.File]::ReadAllBytes($CompFileForEmail))
            #Fill variable for the body of the email
            $ParsedLogEntryEmailBodyData = $null
            $ParsedLogEntryEmailBodyData = Select-String -Path "$LogFileForEmail" -Pattern 'UPDATING:', 'PROCESSING:', 'INFO:', 'ERROR:', 'SYSTEMERROR:' -CaseSensitive:$true | Select-Object Line -ExpandProperty line | ConvertTo-Html -Fragment -As List -Property 'Line' | ForEach-Object { $_ -replace '<td>Line:</td>', '' }
            $HtmlLogFileForEmail = $null
            $HtmlLogFileForEmail = "$env:SystemDrive\Temp\PShellUniversal\ADPFiles\ADPFilteredLogs\ADPSync-FilteredHTML-Log-$session:LogfileTimestamp.html"
            $ParsedLogEntryEmailBodyData | Out-File -FilePath $HtmlLogFileForEmail -Force
            $ADPImportHTMLFileEmailAttachment = $null
            $ADPImportHTMLFileEmailAttachment = [Convert]::ToBase64String([IO.File]::ReadAllBytes($HtmlLogFileForEmail))
            $cache:ADPIRSender = 'ADPImportReport@kvc.org'
            $ADPImportLogReportEmailParams = @{
                Message         = @{
                    Subject      = "PUtility Alert"
                    Body         = @{
                        ContentType = "html"
                        Content     = "$ParsedLogEntryEmailBodyData"
                    }
                    ToRecipients = @(
                        @{
                            EmailAddress = @{
                                Address = $cache:ADPIRRecipient
                            }
                        }
                    )
                    Attachments  = @(
                        @{
                            "@odata.type" = "#microsoft.graph.fileAttachment"
                            Name          = $LogFileForEmail
                            ContentType   = "text/plain"
                            ContentBytes  = $ADPImportLogFileEmailAttachment
                        }
                        @{
                            "@odata.type" = "#microsoft.graph.fileAttachment"
                            Name          = $HtmlLogFileForEmail
                            ContentType   = "text/html"
                            ContentBytes  = $ADPImportHTMLFileEmailAttachment
                        }
                        @{
                            "@odata.type" = "#microsoft.graph.fileAttachment"
                            Name          = $PreFileForEmail
                            ContentType   = "text/csv"
                            ContentBytes  = $ADPImportPreFileEmailAttachment
                        }
                        @{
                            "@odata.type" = "#microsoft.graph.fileAttachment"
                            Name          = $PostFileForEmail
                            ContentType   = "text/csv"
                            ContentBytes  = $ADPImportPostFileEmailAttachment
                        }
                        @{
                            "@odata.type" = "#microsoft.graph.fileAttachment"
                            Name          = $CompFileForEmail
                            ContentType   = "text/csv"
                            ContentBytes  = $ADPImportCompFileEmailAttachment
                        }
                    )
                }
                SaveToSentItems = "true"
            }
            try {
                Send-MgUserMail -UserId $cache:ADPIRSender -BodyParameter $ADPImportLogReportEmailParams
            }
            catch {}
            Disconnect-MgGraph | Out-Null
        }
    } -FullScreen -Persistent
}
function Abort-ADPUploadedCSVImport {
    Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Logging started: $session:LogfileTimestamp" -Force
    Add-Content -Path $session:LogfileExportPathandName -Value "INFO: Log File Location on kvchs-pshell01.kvc.org - $session:LogfileExportPathandName" -Force
    Add-Content -Path $session:LogfileExportPathandName -Value "INFO: The import process was aborted by the user: $User" -Force
    $page:ADPUploadFileValidation = $null
    $page:ADPUploadPathValidation = $null
    Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
}

$ProgressPreference = “SilentlyContinue”
$Navigation = @(
    New-UDListItem -Label 'Active Directory Powershell Tools DEV' -OnClick {
        Invoke-UDRedirect -Url '/ADPowershellTools-DEV'
    }
    New-UDListItem -Label 'Import ADP CSV to AD' -OnClick {
        Invoke-UDRedirect -Url '/ADImportADPCSVtoAD'
    }
)
New-UDApp -Title 'MS AD Dashboard (PowerShell Universal) DEV' -Pages @(
    Get-UDPage -Name 'AD Powershell Tools DEV'
    Get-UDPage -Name 'AD Import ADP CSV to AD'
) -Navigation $Navigation
New-UDPage -Url "/ADPowershellTools-DEV" -Name "AD Powershell Tools DEV" -Content {
    New-UDTypography -Text 'AD Powershell Tools' -Align center -Variant h2
}
New-UDPage -Url "/ADImportADPCSVtoAD" -Name "AD Import ADP CSV to AD" -Content {
    New-UDForm -Id 'UDFImportADPCSVtoAD' -Content {
        #comment to commit checkpoint
        Set-ADPImportFunctionVariableGlobalTimestamp
        Set-ADPUploadFileData
    } -OnValidate {
        Set-ADPImportLogFile
        Validate-ADPUploadFile
    } -OnSubmit {
        Submit-ADPUploadFile
    } -OnCancel {
        Set-ADPImportLogFile
        Abort-ADPUploadedCSVImport
    } -CancelText 'ABORT IMPORT' -DisableSubmitOnEnter:$True -SubmitText 'COMMIT CHANGES TO AD'
}

I still feel like I’m being wildly inefficient, but I don’t work with anyone else who is interested in working on PowerShell, so I have no one to spit ball with. If anyone actually sees this and sees anything glaringly wrong. Please let me know.