PowerShell copy latest file to 2 locations, rename at destination locations
Hi everyone,
I'm leveraging an existing PowerShell script (see below) to work in the following method:
- Only copy the latest file in the source folder to a destination and archive directory (we use a job scheduler app to run every hour).
- Do not touch or move the source
- Drop the prefix of the file which starts with "OPT_" in only the destination and archive (i.e. rename-item to OPT_File_12345.csv to File_123456)
- When the job runs again, it should know not to copy previously copied files but understands they were renamed.
I've tried using -replace to remove the prefix, but now I am coming to realization this will require additional logic. Code is seen below.... can someone help??
# Set the path for our working directories$Source_Folder = '\\pension2\shared\PPSA Dev\Src\'$Archive_Folder = '\\pension2\shared\PPSA Dev\Arc\'$SFTP_Folder = '\\pension2\shared\PPSA Dev\Dst\'# This gets a collection of all of the files in each of our working directories$Source_Files = Get-ChildItem "$Source_Folder\*.csv"$Archive_Files = Get-ChildItem "$Archive_Folder\*.csv"$SFTP_Files = Get-ChildItem "$SFTP_Folder\*.csv"$Found = $False# This loops through each file in the source directory and checks them against both destinations$Source_Files | ForEach-Object { if (!(Test-Path($_.FullName.Replace($Source_Folder, $Archive_Folder)))) { # This is going to output every file we don't find Write-Host "$_.Name not found in $Archive_Folder" # This will Copy every file we didn't find Copy-Item $_.FullName -Destination $Archive_Folder -Verbose Copy-Item $_.FullName -Destination $SFTP_Folder -Verbose # This is a flag we're setting, so we can simply output if no files were found $Found = $True }}# Output that we found no filesif (!($Found)) { Write-Host "No new files found."}
If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.
I have recommended this question be closed as follows:
Accept: oBdA (https:#a42380886)
If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.
Pber
Experts-Exchange Cleanup Volunteer