PowerShell function that serves as a wrapper for the Robocopy (Robust Copy) command utility.
#
# Execute robocopy with parameters as required, proper handling of output,
# proper handling of error codes.
function Robust-Copy {
param(
[string] $sourcePath = $(throw "sourcePath is required"),
[string] $destPath = $(throw "destPath is a required"),
[string[]] $includeFiles = @(),
[string[]] $excludeDirectories = $null,
[string[]] $excludeFiles = $null,
[string[]] $params = @(),
[string] $item = ""
)
Write-Host "Copying '$item' from '$sourcePath' to '$destPath'"
$defaultParams = @("/MIR","/NP","/NFL","/NDL","/NJS","/NC","/NS") # Mirror and be quiet :-)
$xdParams = @()
if ($excludeDirectories -ne $null)
{
$xdParams = @("/XD")
$xdParams += $excludeDirectories
}
$xfParams = @()
if ($excludeFiles -ne $null)
{
$xfParams = @("/XF")
$xfParams += $excludeFiles
}
& "robocopy" $robocommand $sourcePath $destPath $includeFiles $defaultParams $params $xdParams $xfParams | Out-Null
if (($LASTEXITCODE -ge 0) -and ($LASTEXITCODE -le 3))
{
Write-Verbose "Robocopy success: $LASTEXITCODE"
}
elseif (($LASTEXITCODE -gt 0) -and ($LASTEXITCODE -lt 16))
{
Write-Warning "Robocopy exit code: $LASTEXITCODE"
}
elseif ($LASTEXITCODE -eq 16)
{
Write-Host "Robocopy did not copy anything."
}
else
{
Write-Warning "Robocopy unknown exit code: $LASTEXITCODE"
}
}
#
# Example usage:
#
#
# Example 1:
Robust-Copy -sourcePath "$sourceDir" -destPath "$workingSourceDir" -excludeDirectories "bin","obj","TestResults","AppPackages","$packageDirs",".vs","artifacts" -excludeFiles "*.suo","*.user","project.json","*.lock.json" -item "source"
#
# Example 2:
foreach ($build in $builds)
{
# TODO: Can projects and final directories be pulled out of the list of builds?
$prjNames = $build.PrjNames
$finalDir = $build.FinalDir
foreach($prj in $prjNames)
{
Robust-Copy -sourcePath "$workingSourceDir\$prj\bin\Release\$finalDir" -destPath "$workingDir\Package\Bin\$finalDir" -includeFiles "*.dll","*.pdb","*.xml" -excludeFiles "*.CodeAnalysisLog.xml" -item "compiled binaries"
}
}