Reputation: 1
I have a report which needs to be sent out daily. Every morning, I manually using Ctrl + C and make a copy of the report in a specific folder, then open the excel file and refresh the contents. To remove this everyday manual labor, I wrote a power shell script which could automate the task for me.
Script:
$OriginalDir = "C:\Users\101335\Google Drive\BI\Aditya\Daily Order Report"
$BackupDir = "C:\Users\101335\Desktop\Test"
$LatestFile = Get-ChildItem -Path $Originaldir | Sort-Object LastAccessTime -Descending |
Select-Object -First 1
Copy-Item -path "$OriginalDir\$LatestFile" "$BackupDir\$LatestFile"
Get-ChildItem -Path $BackupDir | Rename-Item -newname {"Daily Order Report _India_" +$_.CreationTime.toString("dd.MM.yyyy") + ".xlsx"}
$LatestFile1 = Get-ChildItem -Path $BackupDir | Sort-Object LastAccessTime -Descending |
Select-Object -First 1
Copy-Item "C:\Users\101335\Desktop\Test\*.*" "C:\Users\101335\Google Drive\BI\Aditya\Daily Order Report"
Start-Sleep -s 2
Get-ChildItem -Path $BackupDir -Include * | remove-Item -recurse
Problem:
What I have tried to do is:
I have been able to pursue the steps up to renaming of the file with the current date, but I am not able to copy it back to the original folder.
Can somebody help me out with this?
Upvotes: 0
Views: 149
Reputation: 22821
If you're copying to a backup directory, renaming, copying back to original and then deleting from the backup directory, I don't know why you need to use a backup directory at all - You could just copy the file into the original directory with the new name.
Try:
$OriginalDir = "C:\Users\101335\Google Drive\BI\Aditya\Daily Order Report"
$LatestFile = Get-ChildItem -Path $Originaldir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$LatestFileName = $LatestFile.Name
$LatestFileTime = $LatestFile.CreationTime.toString("dd.MM.yyyy")
Copy-Item "$OriginalDir\$LatestFileName" $("{0}\Daily Order Report _India_{1}.xlsx" -f $OriginalDir, $LatestFileTime)
Upvotes: 2