 
        
        OpsaC - Operating as PowerShell code
published: February 5, 2019 author: Tinu tags: PowerShell categories: PowerShell-Basic
Synchronize a destination directory with content from a source directory and format the output to an object.
function Sync-TargetDirectory{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [String] $Source,
        [Parameter(Mandatory=$true)]
        [String] $Destination
    )
    $function = $($MyInvocation.MyCommand.Name)
    Write-Verbose "Running $($function)($($Source), $($Destination))"
    try{
        $result = robocopy $($Source) $($Destination) /E /R:0 /W:0 /NJH /NP /NFL /NDL
        if(-not([string]::IsNullOrEmpty($result ))){
            $summary = (($result -match 'Files :' -replace '\s+','@').TrimStart('@Files:@') -split '@')
            if(($summary[4]) -eq 0){
                $Succeeded = $true
            }
            else{
                $Succeeded = $false
            }
            $ret = [PSCustomObject]@{
                Succeeded = $Succeeded
                Total     = $summary[0]
                Copied    = $summary[1]
                Skipped   = $summary[2]
                Mismatch  = $summary[3]
                FAILED    = $summary[4]
                Extras    = $summary[5]
            }
        }
    }
    catch [Exception]{
        Write-Verbose "-> Catch block reached"
        $ret = [PSCustomObject]@{
            Succeeded  = $false
            Function   = $function
            Activity   = $($_.CategoryInfo).Activity
            Message    = $($_.Exception.Message)
            Category   = $($_.CategoryInfo).Category
            Exception  = $($_.Exception.GetType().FullName)
            TargetName = $($_.CategoryInfo).TargetName
        }
        $error.clear()
    }
    return $ret
}
$sync = Sync-TargetDirectory -Source $srcdir -Destination $dstdir -Verbose
$sync | ft
Succeeded Total Copied Skipped Mismatch FAILED Extras
--------- ----- ------ ------- -------- ------ ------
     True 180   148    32      0        0      0
Robocopy on Microsoft Docs.