Skip to content

Instantly share code, notes, and snippets.

@ninmonkey
Last active August 19, 2024 19:33
Show Gist options
  • Save ninmonkey/ce5ae53f921463a958c87380d00de6b3 to your computer and use it in GitHub Desktop.
Save ninmonkey/ce5ae53f921463a958c87380d00de6b3 to your computer and use it in GitHub Desktop.
Robocopy, a simple wrapper
using namespace System.Collections.Generic
$RoboAppConf ??= @{
Root = $PSScriptRoot | Get-Item
Log = @{
Path = Join-Path (Get-item 'temp:') 'last-robocopy.log'
}
}
function Invoke-Robocopy {
<#
.SYNOPSIS
a simple robocopy wrapper
.notes
If you are using WinPS5 you might need to wrap Get-Item
with an explicit $foo.FullName or wrap explicit double quotes
pwsh simplifies that a bit
To change native arg parsing, checkout: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing?view=powershell-7.4#passing-arguments-that-contain-quote-characters
.EXAMPLE
$From = 'c:\backup\2018\art'
$to = 'd:\data\art'
Invoke-RoboCopy -SourcePath $From -DestPath $to -WhatIf
.EXAMPLE
# a test run, using -RoboWhatIf
# which means run robocopy with '/L'
$From = 'c:\backup\2018\art'
$to = 'd:\data\art'
Invoke-RoboCopy -SourcePath $From -DestPath $to -RoboWhatIf
#>
[CmdletBinding()]
param(
# folder to save
[Parameter(Mandatory, Position = 0)]
[string] $SourcePath,
# folder destination
[Parameter(Mandatory, Position = 1)]
[string] $DestPath,
# view command args, and also uses '/L' for robocopy
# robocopy specific whatif, the '/L'
[Alias('TestRun')]
[switch] $RoboWhatIf,
# regular WhatIf
[switch]$WhatIf,
# as a switch
[Alias('NoETA')][switch] $WithoutETA,
[string[]] $NotUsing = @(),
[hashtable] $Options
)
$binRobo = Get-Command 'RoboCopy' -CommandType Application -ea stop
New-Item -Path $RoboAppConf.Log.Path -ItemType File -ea ignore
if (-not(Test-Path $DestPath)) {
'Path does not exist, create it? "{0}"' -f @( $DestPath )
mkdir -Path $DestPath -Confirm -Verbose
}
[List[Object]]$RoboArgs = @(
(Get-Item -ea stop $SourcePath )
(Get-Item -ea stop $DestPath )
'/S'
'/COPY:DAT'
'/UNICODE'
'/UNILOG:{0}' -f @( $RoboAppConf.Log.Path | Get-Item -ea stop )
# '/UNILOG:lastBig.basic.log' -f @( )
'/tee'
if ( $RoboWhatIf ) { '/L' }
if ( -not $WithoutETA) { '/ETA' }
)
$renderRoboArgs = $RoboArgs | Join-String -sep ' ' -op 'robocopy.exe args: '
$renderRoboArgs | Write-Information
$renderRoboArgs | Write-Verbose
if ($WhatIf) {
$renderRoboArgs
return
}
if ($PSCmdlet.ShouldProcess('CopyFiles', 'RoboCopy')) {
& RoboCopy @RoboArgs
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment