简体   繁体   中英

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

在此处输入图像描述

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')}
}

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM