Search code examples
arrayspowershellif-statementrangecopy-item

How can I use PowerShell to copy a range of files where the file name is as sequence of numbers


How can I use PowerShell to copy a range of files where the file name is as sequence of numbers?

For example, say I have a bunch of files where the names are numbers starting at 23540987577 to 27495847547388. However I only want to copy files where the middle 5 numbers are between 43565 and 43769. I have made a few attempts, but it either copies everything, or errors out.

So far I have the following :

    $START = read-host -prompt "Enter starting number"
$END = read-host -Prompt "Enter ending number"


$Files = Get-ChildItem
$Files = $Files.name
$i = 1
foreach ($i in $Files) {
if ($Files[$i] -ge "*$START*" -and $Files[$i] -le "*$END*") {
/
Copy-Item $Files[$i] .\pulled
$i++
}
else {
Write-Host "no"

}
}

I have a list of files where the file name is a large sequence of numbers. Within said sequence (some where towards the middle) is a transaction number. I need to find and copy a small subset of transaction numbers that are within a specific range.

If I am searching for said files manually in Windows Explorer I would have search for each number in the range as follows:

*43565*
*43566*
*43567*
*43568*

and so on...

I want to automate this process as it takes a long time to search for each transaction number with larger batches.


Solution

  • what about the following:

    it's not regex but I dont see any advantage of using regex here:

    I didn't use much Powershell yet, therefore I stick to Pseude Code, but you should be able to adapt this to Powershell script easily:

    CopyFiles(int lowerBound, int upperBound)
    {
        foreach (file in fileList)
        {
             int filename = (int)file.filename.substring(1,X) // you have to know the length of your substring, maybe pass it also as parameter
             if(filename >= lowerBound && filename <= upperBound)
             {
                 move (file.filename, new location)
             }
        }
    }