Tinus EngOps Wiki

Logo

OpsaC - Operating as PowerShell code

Links

Home

PowerShell Blog

PowerShell Index

PowerShell Search

Additional Websites

View my GitHub Profile

View my GitHub Gists

View Tinus IT Wiki

View my Photo Website

Synchronize Folder

published: February 5, 2019 author: Tinu tags: PowerShell categories: PowerShell-Basic


Table of Contents

Synchronize with Robocopy

Synchronize a destination directory with content from a source directory and format the output to an object.

Function Sync-TargetDirectory

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

Output from Sync-TargetDirectory

Succeeded Total Copied Skipped Mismatch FAILED Extras
--------- ----- ------ ------- -------- ------ ------
     True 180   148    32      0        0      0

See also

Robocopy on Microsoft Docs.


← Previous Post [ Top ] Copyright © 2024 by tinuwalther [ Blog ] Next Post →