troubleshooting Question

PowerShell copy latest file to 2 locations, rename at destination locations

Avatar of OPT Expert
OPT Expert asked on
PowershellActive Directory
2 Comments1 Solution560 ViewsLast Modified:
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 files
if (!($Found)) {
    Write-Host "No new files found."
Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros