Copy files with loading variables using PowerShell

In this blog, We will see how we can copy files from one folder to another folder using PowerShell and the file path should be loaded from the config file as variables.

Let’s say we receive daily files in two different folders for SG/HK location and we need to copy these source folders all files to destination folder SG/HK location. eg.

Step-1 – Declare variables with source and destination paths (vars.txt).

SG_SOURCE=C:\logs\source\SG
SG_DESTINATION=C:\logs\destination\SG

HK_SOURCE=C:\logs\source\HK
HK_DESTINATION=C:\logs\destination\HK

Step-2 – Load variables from the vars file and split with (=) to get the path.

 # reading path from var files
$props_file = Get-Content "C:\logs\vars.txt"
$props = @{}
$props_file | % {
    $s = $_ -split "="
    $props.Add($s[0],$s[1])
}

Step-3 – Retrieve path details from props variable for SG/HK source and destination path.

#sg source and destination files 

$the_sourcedir = $props.'SG_SOURCE'
Write-Host $the_sourcedir

$the_destinationdir = $props.'SG_DESTINATION'
Write-Host $the_destinationdir 

#hk source and destination files 

$the_sourcedir_hk = $props.'HK_SOURCE'
Write-Host $the_sourcedir_hk

$the_destinationdir_hk = $props.'HK_DESTINATION'
Write-Host $the_destinationdir_hk 

Step-4 – Copy the files from SG source folder to SG destination folder .

 
#copying files from sg source to sg destination 
Copy-Item -Path $the_sourcedir\* -Destination $the_destinationdir 

Step 5– Copy files from SG/HK source folders to SG destination folder .

 Copy-Item -Path $the_sourcedir\*,$the_sourcedir_hk\* -Destination $the_destinationdir 

Refer code – https://github.com/asifwaquar/copy-item-powershell/

Leave a Reply

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