Asked by:
Move filenames based on pattern

Question
-
I was trying to build a script to move specific files from one location to another. When I run this script with powershell it also moves files with the wrong pattern. For example below I would like to move specific file name which names start with 40001- or higher and less then 50000-.
Get-ChildItem $path -file | Where-Object { $_.Name -gt "40001+-*" -and $_.Name -lt "50000+-*" } | Move-Item -destination $path -whatif
If we have a look to the result, we can see that also filenames which didnt had to be moved like 432412... and 432416... are listed to move while only 40003... twice should had been moved. Can somebody tell me what I'm doing wrong?
Result:
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 24-5-2007 10:56 537510 40003-ABS-01022006.pdf
-a---- 28-11-2013 14:11 163500 40003-DRINK-04122013.pdf
-a---- 20-9-2018 14:37 40120 432412-cathver-10092018.pdf
-a---- 11-9-2018 08:32 451972 432416-cathver-11092018.pdfTuesday, October 2, 2018 1:18 PM
All replies
-
you should convert the numeric part to an integer if you want to use GT or it may treat it as a string.Tuesday, October 2, 2018 1:34 PM
-
Can you show me the command I need to use?Tuesday, October 2, 2018 2:16 PM
-
$a = "432412-cathver-10092018.pdf"
$b = [INT]$a.split("-")[0]
Tuesday, October 2, 2018 2:51 PM -
Thanks! only next step.. How to move the file then after split it?Thursday, October 4, 2018 6:55 AM
-
Below script will get all files from $sourcePath containing a '-' in the file name. It will then check in a foreach loop if the integer value is greater then 40001 and less then 50000. If so, it will move the file to the $destinationPath.
$sourcePath = "C:\source" $destinationPath = "C:\destination" $allItems = Get-ChildItem $sourcePath -File | Where-Object { $_.Name -match '-' } foreach ($item in $allItems) { [int]$fileInt = $item.Name.split("-")[0] if($fileInt -gt 40001 -and $fileInt -lt 50000) { $item | Move-Item -Destination $destinationPath -WhatIf } }
Thursday, October 4, 2018 7:47 AM -
Or if you prefer a 'one-liner'
$sourcePath = "C:\source" $destinationPath = "C:\destination" Get-ChildItem $sourcePath -File | Where-Object { $_.Name -match '-' -and [int]$_.Name.split("-")[0] -gt 40001 -and [int]$_.Name.split("-")[0] -lt 50000 } | Move-Item -Destination $destinationPath -WhatIf
Thursday, October 4, 2018 7:50 AM -
Thanks! this works:)Friday, October 5, 2018 6:16 AM