简体   繁体   中英

How to handle copy file with infinity loop 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 can do this part refer to this great answer How to copy file based on matching file name using PowerShell? https://stackoverflow.com/a/58182359/11066255

But I want to do this process with infinity loop. Once I use infinity loop, I found that I have a lot of duplicate file. How do I make limitation, if I already copy the file, I will not copy again in the next loop. Anyone can help me please. Thank you. 在此处输入图像描述

for(;;)
{
$Job_Path = "D:\Initial"
$JobError = "D:\Process"

Get-ChildItem -Path "$OpJob_Path\*\*.jpg" | ForEach-Object {
    $basename = $_.BaseName.Substring(15)
    $job = "$Job_Path\${basename}.png"
    if (Test-Path $job) {
        $timestamp = Get-Date -Format 'yyyyMMddhhmmss'
        $dst = Join-Path $_.DirectoryName "${timestamp}_${basename}.gif"
        $Get = (Get-ChildItem -Name "$OpJob_Path\*\*$basename.jpg*" | Measure-Object).Count
        Copy-Item $job $dst -Force
    }
}
}

File management 101 is that, Windows will not allow duplicate file names in the same location. You can only have duplicate files, if the name of the file is unique, but the content is the same. Just check for the filename, but they must be the same filename, and do stuff if it is not a match else do nothing.

Also, personally, I'd suggest using a PowerShell FileSystemWatcher instead of a infinite loop. Just saying...

This line …

$timestamp = Get-Date -Format 'yyyyMMddhhmmss'

… will always generate a unique filename by design, the content inside it is meaningless, unless you are using file hashing for the compare as part of this.

Either remove / change that line to something else, or use file hash (they ensure uniqueness regardless of name used)...

Get-FileHash -Path 'D:\Temp\input.txt'

Algorithm       Hash                                                                   Path
---------       ----                                                                   ----
SHA256          1C5B508DED35A28B9CCD815D47ECF500ECF8DDC2EDD028FE72AB5505C0EC748B       D:\Temp\input.txt

... for compare and prior to the copy if another if/then.

something like...

If ($job.Hash -ne $dst.Hash)
{Copy-Item $job.Path $dst.Path}
Else
{
    #Do nothing
}

There are of course other ways to do this as well, this is just one idea.

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