Monday, October 23, 2023

Data Transfer and Error Tracking: A PowerShell Script for Copying Files with Confidence

This PowerShell script serves as a versatile and robust tool for copying files from a source directory to a destination directory while keeping track of any files that could not be found during the copy operation. The script is meticulously documented and parameterized for ease of use, making it suitable for various file transfer and backup tasks.

Script Components:

  1. Synopsis and Description: The script begins with a clear and informative synopsis and description section to provide users with an understanding of its purpose and functionality.
  2. Parameters:
    • $sourcePath: This parameter allows you to specify the source directory from which files will be copied.
    • $destinationPath: You can specify the destination directory where the files will be copied.
    • $errorLogPath: This parameter enables you to designate the path to an error log file where the script will record the paths of files that couldn't be located or copied.
  3. Destination Directory Creation: The script checks if the destination directory specified in $destinationPath exists. If it does not exist, the script creates the directory to ensure a valid destination for the file copies.
  4. Error Log Initialization: An array named $notFoundPaths is initialized to store paths to files that the script couldn't locate or copy successfully.
  5. File Copying Process:
    • The script uses the Get-ChildItem cmdlet to recursively find all files in the source directory.
    • For each file found, it enters a ForEach-Object loop to perform the following actions:
      • It constructs the full path of the source and destination files.
      • It attempts to copy the file from the source to the destination using Copy-Item.
      • In case an error occurs during the copy operation, the script captures the error message and the source file's path. It logs the error message using Write-Host, and the path is appended to the $notFoundPaths array.
  6. Error Logging:
    • After the file copying process is complete, the script checks if there are any paths stored in the $notFoundPaths array.
    • If there are paths in the array (indicating files that couldn't be copied), the script appends these paths to the error log file specified in $errorLogPath. This provides a comprehensive record of files that could not be successfully copied, aiding in troubleshooting and error resolution.

Use Cases:

This PowerShell script is highly useful in various scenarios, such as:

  • Backing up files from one location to another.
  • Migrating data between folders or drives.
  • Maintaining a record of files that couldn't be copied due to permission issues or other errors.
  • Automating file transfer tasks within a scheduled or batch process.

The script's parameterized design ensures flexibility, making it adaptable to different source and destination directories and enabling you to customize the error log file's location. Its error handling mechanism ensures that even in the event of failures during the copying process, you have a clear record of what went wrong.




<#

.SYNOPSIS

    This script copies files from a source directory to a destination directory while logging any paths that couldn't be found.

 

.DESCRIPTION

    This PowerShell script recursively copies files from a source directory to a destination directory, ignoring subfolders.

    If any files cannot be found during the copying process, it logs their paths to an error log file.

 

.PARAMETER sourcePath

    Specifies the source directory from which files will be copied.

 

.PARAMETER destinationPath

    Specifies the destination directory where files will be copied to.

 

.PARAMETER errorLogPath

    Specifies the path to the error log file where paths of files that couldn't be found will be logged.

 

.NOTES

 

    Author: Navinya Ambre

    Date: 10/10/2023

 

#>

 

param (

    [string]$sourcePath,

    [string]$destinationPath,

    [string]$errorLogPath

)

 

# Create the destination directory if it doesn't exist

if (-not (Test-Path -Path $destinationPath -PathType Container)) {

    New-Item -Path $destinationPath -ItemType Directory

}

 

# Initialize an array to store paths that couldn't be found

$notFoundPaths = @()

 

# Recursively copy all files from source to destination, ignoring subfolders

Get-ChildItem -Path $sourcePath -File -Recurse | ForEach-Object {

    $sourceFile = $_.FullName

    $destinationFile = Join-Path -Path $destinationPath -ChildPath $_.Name

 

    try {

        Copy-Item -Path $sourceFile -Destination $destinationFile -Force -ErrorAction Stop

    } catch {

        # If an error occurs during the copy, log the error message and path to the error log

        $errorMessage = $_.Exception.Message

        Write-Host "Error: $errorMessage"

        $notFoundPaths += $sourceFile

        $errorMessage | Out-File -FilePath $errorLogPath -Append

    }

}

 

# Log the paths that couldn't be found to a text file

if ($notFoundPaths.Count -gt 0) {

    $notFoundPaths | Out-File -FilePath $errorLogPath -Append

}


Please consider this an open forum for sharing your thoughts, modifications, and suggestions regarding the script. Your input and feedback are highly encouraged and valued.

No comments:

Post a Comment