Joe
Joe

Reputation: 45

How to copy file based on matching file name using PowerShell?

enter image description here

I want to check .jpg file in the 2nd folder. 2nd folder has some subfolder. if .jpg exist in the subfolder of 2nd folder, I will copy a file from 1st folder to subfolder of 2nd folder based on the base name. I tried this code, I can check the existence of .jpg, then match the file to 1st folder file. My problem, I can not copy if the file .jpg more than 1 and when I copy the file, I can not specify which subfolder that I should copy.

I tried this:

$JobInit  = "D:\Initial"
$JobError = "D:\Process"

if (Test-Path -Path "$JobError\*\*.jpg") {
    Write-Host "Error Exist"
    $L_Name = "15"
    $ErrorFile = Get-ChildItem -Path "$JobError\*\*.jpg" |
                 ForEach-Object { $_.BaseName.Substring($L_Name) }

    $Path_ = Get-ChildItem -Path "$JobError\*\*.jpg"
    $Split = Split-Path -Path $Path_

    $NewJob = @(Get-ChildItem -Path "$JobInit\*.png" -File -Recurse |
              Where-Object { "$ErrorFile" -contains $_.BaseName })
    Write-Host $NewJob

    $Timestamp = Get-Date -Format yyyyMMddhhmmss
    $CopyJob = Copy-Item $NewJob -Destination "$Split"
    $Rename = Get-ChildItem "$Split\*.png" |
              Rename-Item -NewName {"$Timestamp`_" + $_.Name.Replace('.png','.gif')}
}

Upvotes: 0

Views: 424

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200553

Assuming that I understood your question correctly and you want to replace existing JPEG files in the "Process" folder if they have a corresponding PNG file in the "Initial" folder, the following should do the trick:

$L_Name = 15
Get-ChildItem -Path "$JobError\*\*.jpg" | ForEach-Object {
    $basename = $_.BaseName.Substring($L_Name)

    $png = "$JobInit\${basename}.png"
    if (Test-Path $png) {
        $timestamp = Get-Date -Format 'yyyyMMddhhmmss'
        $dst = Join-Path $_.DirectoryName "${timestamp}_${basename}.jpg"
        Copy-Item $png $dst -Force
    }
}

Upvotes: 1

Related Questions