简体   繁体   中英

Moving files named with a number

Please assist, I want to only move file with with either a 1 or 2 on the file name. eg: text1.txt,text2.txt,text3.txt,text4.txt,text5.txt only text1.txt and text2.txt must be moved. My PowerShell script copies all the files.

As your question is not clear, I'm not sure whether this is what you are looking for or not.

However, following example may be useful. I created an array named pattern1 that contains 2 elements: text1.txt and text2.txt . When you run the script, it asks you to press enter to continue. Once the execution's completed, you'll notice that it prints out the process details(How many of files were in the folder and how many are copied):

$SourceFolder = "D:\TestFolder\"
$targetFolder = "D:\TestFolder\Destination\"
$numFiles = (Get-ChildItem -Path $SourceFolder -Filter *.TXT).Count
$pattern1 = "text1.txt","text2.txt"
$i=0

clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $SourceFolder ' to ' $targetFolder
Read-host -prompt 'Press enter to start copying the files'

Get-ChildItem -Path $SourceFolder -Filter *.TXT | %{ 
    [System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace("_","\"))

   if(!(Test-Path -Path $destination.Directory )){
    New-item -Path $destination.Directory.FullName -ItemType Directory 
    }
    [int]$percent = $i / $numFiles * 100

    if($pattern1.Contains($_.Name)){
    copy-item -Path $_.FullName -Destination $Destination.FullName
    Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
    $i++}
}
Write-Host 'Total number of files read from directory '$SourceFolder ' is ' $numFiles
Write-Host 'Total number of files that was copied to '$targetFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;

It can be more generalized for the sake of automation. As an example, you can modify it to check the elements of the array( pattern1 in this case) and copies the files if any file contains that element(of array/ pattern1 ) within its name.

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