PowerShell script is to automate the process of copying a file from a source directory to a destination directory
Purpose of the Script
The purpose of this PowerShell script is to automate the process of copying a file (abc.xlsx) from a source directory to a destination directory, ensuring that:
- The source file exists before attempting any further actions.
- The destination directory exists or is created if it doesn't.
- No overwriting of existing files occurs in the destination directory. If a file with the same name already exists, the script appends a numeric counter (-1, -2, etc.) to the filename to ensure that each copied file has a unique name.
- Safe file operations are ensured by checking for file existence and automatically generating a unique file name when necessary.
Main Use Case:
This script is useful when automating tasks like backing up files, copying reports, logs, or other documents, where the filenames may need to be adjusted based on the date or incremented to avoid conflicts with existing files.
It ensures that the latest copy of the file is always transferred to the destination directory without any risk of overwriting existing files.
In summary, this script is designed to automate the process of file copying, making it safe, efficient, and organized, especially in environments where files with the same name (but potentially different versions) need to be handled daily or periodically.
backupfile.ps1
# Author: LE VAN CUONG
# Website: https://infra.lecuong.info/
# Purpose: Copy a file to another location to back it up.
# - ensure that the destination file always starts with the name "src_name_$current_date.xlsx",
# - if a file with that name already exists, it should be renamed by appending a counter (-1, -2, etc.) until a unique filename is found.
$src_file = "C:\tmp\abc.xlsx"
$dest_dir = "C:\tmp2"
$current_date = Get-Date -Format "yyyyMMdd" # Current date in the format YYYYMMDD
$new_file_name = "abc_$current_date.xlsx"
$dest_file = Join-Path -Path $dest_dir -ChildPath $new_file_name
# 1. Check if $src_file exists, then exit if not found
if (-not (Test-Path -Path $src_file)) {
exit
}
# 2. Check if $dest_dir does not exist, then create it (force)
if (-not (Test-Path -Path $dest_dir)) {
Write-Host "Destination directory '$dest_dir' does not exist. Creating it."
New-Item -Path $dest_dir -ItemType Directory -Force
}
# 3. Check if $dest_file already exists, and if so, rename it with a number suffix
$counter = 1
$new_dest_file = $dest_file
while (Test-Path -Path $dest_file) {
$new_dest_file = $dest_file -replace '\.xlsx$', "-$counter.xlsx"
# Update $dest_file to include the counter (e.g., abc_20240612-1.xlsx)
if (Test-Path -Path $new_dest_file) {
$counter++
continue
}
# Renaming the existing file
Rename-Item -Path $dest_file -NewName "$new_dest_file"
Write-Host "Rename '$dest_file' to '$new_dest_file'" -ForegroundColor Red
}
# 4. Copy the file to the destination with the new name
Copy-Item -Path $src_file -Destination $dest_file
Write-Host "File '$src_file' copied to '$dest_file'" -ForegroundColor Green
Write-Host "Done."
VBScript to run powershell (silent)
backupfile.vbs
Set objShell = CreateObject("WScript.Shell")
objShell.Run "powershell.exe -ExecutionPolicy Bypass -File ""C:\Path\To\Your\Script\backupfile.ps1""", 0, False
SCHEDULED TASK TO RUN VBScript
Open Task Scheduler --> create Task
- General tab(*):
- Name: Backup file
- Run with highest privileges.
- Triggers tab --> New
- Daily
- Repeat task every: 5 minutes
- Actions tab: --> New
- Set the action to "Start a program".
- Program/script: wscript.exe
- Add arguments (optional): C:\Path\To\Your\Script\backupfile.vbs
- Conditions tab: uncheck all (if yes)
- Settings tab:
- Check "Allow task to be run on demand".
Click "OK" to create task
Click on Task to run it.
That's all.