Public/Copy-Folder.ps1
Function Copy-Folder { <# .SYNOPSIS This is a basic overview of what the script is used for.. .DESCRIPTION Thid command compares folders .NOTES Name: Compare-Folder Author: Mark Evans DateCreated: 2021-02-19 .EXAMPLE Compare-Folder -Name "Joe Bloggs" .LINK #> [CmdletBinding(SupportsShouldProcess)] param( #Specifies an array of folders used as a reference for comparison. [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0 )] [ValidateScript( { Test-Path $_ -PathType 'Container' })] [System.IO.DirectoryInfo[]] $ReferenceFolder, #Specifies the folder that is compared to the reference folders. [Parameter(Mandatory, Position = 1)] [ValidateScript( { Test-Path $_ -PathType 'Container' })] [System.IO.DirectoryInfo] $DifferenceFolder, # Specifies the file to backup to [Parameter()] [System.IO.FileInfo] $Archive ) BEGIN { Write-Debug -Message "BEGIN $($MyInvocation.MyCommand) : Version $($MyInvocation.MyCommand.Version)" $FilesToBackup = @() $FilesToCopy = @() } PROCESS { Write-Debug -Message "PROCESS $($MyInvoication.MyCommand)" foreach ($instanceReferenceFolder in $ReferenceFolder) { $Result = Compare-Folder $instanceReferenceFolder $DifferenceFolder $FilesToCopy += $Result | Where SideIndicator -eq '<=' | ForEach-Object { $_ | Add-Member -MemberType NoteProperty -Name "DestinationFullName" -Value $_.FullName.Replace($instanceReferenceFolder, $DifferenceFolder) -PassThru } $CopyDestList = $FilesToCopy | Select -ExpandProperty DestinationFullName $FilesToBackup += $Result | Where { $_.SideIndicator -eq '=>' -and $CopyDestList -contains $_.FullName } } } END { Write-Debug -Message "END: $($MyInvoication.MyCommand)" if ($Archive -and ($FilesToBackup.Length -gt 0) -and $PSCmdlet.ShouldProcess("$Archive", "Backing up $($FilesToBackup.Count) Files")) { $parent = [System.IO.Path]::GetTempPath() $name = [System.IO.Path]::GetRandomFileName() $tempFolder = New-Item -ItemType Directory -Path (Join-Path $parent $name) foreach ($file in $FilesToBackup) { Copy-Item $file.FullName (Join-Path $tempFolder $file.FullName.Replace($DifferenceFolder, '')) -Force } Compress-Archive (Join-Path $tempFolder '*') -DestinationPath $Archive -Force Remove-Item -Path $tempFolder -Recurse -Force } if ($PSCmdlet.ShouldProcess("$DifferenceFolder", "Copying $($FilesToCopy.Count)")) { $FilesToCopy | ForEach-Object { try { $file = $_ Copy-Item $_.FullName $_.DestinationFullName -Force -ErrorAction SilentlyContinue } catch { Write-Output "Failed to Copy $($file.Name)" } } } } } if ((Get-PSCallStack | Measure-Object).Count -eq 1) { .\Compare-Folder.ps1 Copy-Folder C:\MNP\SQLData C:\MNP\Software -Archive C:\mnp\Backup\test.zip Remove-Item Function:Copy-Folder #Remove-Item function:Compare-Folder } |