NZJames
NZJames

Reputation: 5055

How to copy data for a range of dates in script?

My requirement is to take a list of folder paths - some with a yyyyMMdd date in the path - and to copy them to another location on request.

Some folders just need to be copied as is Some need to have five days history copied, calculating the previous five dates and substituting them into the folder path Some need to do the same but for 15 or 90 days history.

I'm trying to determine the best way to do this. I was originally going to do it as a BATCH file but I can't see how to calculate and substitute dates in a loop in BAT.

Is there a better way of doing this in a basic script that can be executed from the command line?

Upvotes: 0

Views: 790

Answers (1)

Tyler Helder
Tyler Helder

Reputation: 624

# Get-Date is a cmdlet in PowerShell to get the current date
# We use AddDays(-5) to subtract however many days we would like. Here we are subtracting 5 days from current date
# ToString converts the data type so that we can use the custom date format of yyyyMMdd
$Date = (Get-Date).AddDays(-5).ToString('yyyyMMdd')

# Get-Item cmdlet in PowerShell is used to get files in a directory
# Select allows us to get a specific piece of data from the files found and ExpandProperty hides the data header
$Files = Get-Item -Path C:\Temp\*$Date.txt | Select -ExpandProperty FullName

# Copies Files Found with Get-Item
Copy-Item -Path $Files -Destination C:\SomePathHere-Verbose -Force

Output would look like the following:

PS C:\> $Date = (Get-Date).AddDays(-5).ToString('yyyyMMdd')

# What is stored in $Date variable
PS C:\> $Date
20160708

PS C:\> $Files = Get-Item -Path C:\Temp\*$Date.txt | Select -ExpandProperty FullName

# What is stored in $Files variable
PS C:\> Get-Item -Path C:\Temp\*$Date.txt | Select -ExpandProperty FullName
C:\Temp\Somefile20160708.txt
C:\Temp\SomeOtherFile20160708.txt

PS C:\> Copy-Item -Path $Files -Destination C:\Test -Verbose -Force
VERBOSE: Performing the operation "Copy File" on target "Item: C:\Temp\Somefile20160708.txt Destination: C:\Test\Somefile20160708.txt".
VERBOSE: Performing the operation "Copy File" on target "Item: C:\Temp\SomeFile220160708.txt Destination: C:\Test\SomeOtherFile220160708.txt".

PowerShell is great for these types of tasks, I definitely recommend exploring it more.

Upvotes: 3

Related Questions