PowerShell script to copy file from one location to another

Table of Contents

  1. Introduction
  2. Scenario
  3. Script
    3.1. Screen shot
    3.2. PowerShell Script
  4. Conclusion
  5. End of Document

PowerShell script to copy file from one location to another

1. Introduction

Purpose of this document is to explain how to copy a file from one location to another location via PowerShell where file name having date format.

This PowerShell script is created on request of one of my subscriber. Hope you will enjoy. If you have any query or concern please contact me at nirajsrivastava1@gmail.com.

2. Scenario

  • User wants to copy SQL backup file from one location (Ex: O:\Backup) to different network path \\ComputerName\SharedPath in Folder with current date.
  • Only current dated file should be copied to destination.
  • Once file copied user should receive file copied status (File name and Size)

3. Script

3.1. Screen shot

3.2. PowerShell Script

## Owner : Niraj Srivastava
## Date : 11-Feb-2020
## Version : 1.0 
## Copy daily backup files to different location

$str = "*" * 130
$dt= (Get-Date).ToString("dd-MMM-yyyy")

$hr= (get-date).hour
$min = (get-date).minute
$sec = (get-date).second
$starttm = "$hr"+":"+"$min"+":"+"$sec"

write $str
Write "Copy Date :$dt time: $starttm $fileDT" 

# Change the source path from where you want to copy

# Provide IP or hostname where you want to copy the file

# Create folder at distination with current Date
# Make sure the user executing the script have sufficient rights to create folder and folders at destination

New-Item  -Path "$destPath" -Name "$dt" -ItemType "directory" -ErrorAction SilentlyContinue
Copy-Item $sourPath\NSITDB\NSITDB_$file_dt*.bak $destPath\$dt
Copy-Item $sourPath\master\master_backup_$file_dt*.back $destPath\$dt
Copy-Item $sourPath\model\model_$file_dt*.log $destPath\$dt

# Send email about file copied at destination with file size
# System should be able to reachanble to SMTP server
$output=Get-Item $destPath\$dt\*  | select Name, Length | ft
Write "File copied to $destPath"
write $output
Send-MailMessage -To niraj.srivastava@nsitautomation.in -From donotreply@nsitautomation.in -SmtpServer nsitautomation.in -Subject "Backup Status $fileDT" -Body $output 

4. Conclusion

PowerShell Script will create a folder with current date at destination and copy only latest files from source.

If it works for you please share, comment and like. Thank you.

5. End of Document

Facebook Comments

One thought to “PowerShell script to copy file from one location to another”

  1. Superb Niraj……Very informative….Please keep posting.

Leave a Reply

Your email address will not be published. Required fields are marked *