# ======================================================================================================
# .DESCRIPTION
# Copies the items of the specified source folder to the specified destination folder one by one
# .PARAMETER SourceFolder
# Mandatory. The path of the source folder from which to copy the files
# .PARAMETER DestinationFolder
# Mandatory. The path of the destination on which to copy the files to
# .PARAMETER DestinationFolder
# Optional. Whether the items should be sorted by name descending instead of ascending
# .EXAMPLE
# Copy-FilesByName -SourceFolder "C:\Temp" -DestinationFolder "C:\Temp2"
# ======================================================================================================
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[String]$SourceFolder,
[ValidateNotNullOrEmpty()]
[String]$DestinationFolder,
[switch]$Descending
)
Process
{
Try
{
# Ensures the source folder
Write-Host ("Ensuring source folder with path '{0}'..." -f $sourceFolder);
$sourceFolderExists = Test-Path $sourceFolder;
if(!$sourceFolderExists) {
throw ("The specified source folder with path '{0}' was not found." -f $SourceFolder);
}
# Ensures the destination folder
Write-Host ("Ensuring destination folder with path '{0}'..." -f $DestinationFolder);
New-Item -ItemType Directory -Force -Path $DestinationFolder | Out-Null;
# Sorts the source folder items by name/ascending
Write-Host ("Sorting items by name ascending...");
$sortedSourceItems = Get-ChildItem -Path $SourceFolder | Sort Name;
if($Descending) {
$sortedSourceItems = $sortedSourceItems | Sort Name -Descending;
}
# Copies the sorted items one by one
$sortedSourceItems | ForEach-Object {
Write-Host ("Copying item '{0}' to destination folder..." -f $_.FullName);
$_ | Copy-Item -Destination $DestinationFolder;
}
Write-Host ("Items have been copied successfully...") -foreground green;
}
Catch
{
throw ("An error occured while copying files from folder '{0}' to folder '{1}' : {2}" -f $SourceFolder, $DestinationFolder, $_.Exception.Message);
}
}