-1

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.

Mali
  • 1
  • 1
  • $_Source = "C:\SourceFolder" path contains : text1.txt,text2.txt,text3.txt,text4.txt,.. files. All the files end with a number eg. text1.txt so I want to move files containing a number 1 or 2 to the destination folder $_Destination = "C:\DestinationFolder" $_A_files = Get-ChildItem -Path $_Source -File -Force -Recurse foreach ($file in A_files) { $fileno = $file.Name.Substring(5,1) If((1 -eq $fileno) -or (2 -eq $fileno)) { Move-item $file.FullName –destination "C:\DestinationFolder { } This will just move all the files.Thanks – Mali Mar 15 '22 at 00:35
  • I've already answered your question. –  Mar 15 '22 at 01:53

1 Answers1

0

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.