Question

I would like to do all 8k+ files at once using the pattern since the left 5 chars of the file matches the right 5 of the sub-directory to move to.

This works one by one:

move-item -path X:\"Property Files"\05165*.pdf -destination X:\"Property Files"\"* -- 05165";
move-item -path X:\"Property Files"\05164*.pdf -destination X:\"Property Files"\"* -- 05164";

Thank you in advance for any help.

Was it helpful?

Solution

As a one-liner, assuming destination folder already exist:

Get-ChildItem "X:\Property Files\*.PDF" | 
 ForEach { move -path $_ -destination ($_.directoryname +"\* -- "+ $_.Name.substring(0,5))}

Using only the filename, you just extract the first five chars (substring(0,5)), then use it as the end of the folder to match.
$_.Directoryname assume destination folder is a subfolder of the source path.

OTHER TIPS

Ok, you're on the right path with the whole RegEx tag here. What I did is look for everything until the last backslash, then captured 5 digits, then everything that isn't a backslash until the end of the line, and only returned the captured group. I set that as a variable $ItemNumber, and used that in the destination. I ran that on a ForEach loop for everything in the target source folder. Here's the code I ended up with:

ForEach($File in (GCI "X:\Property Files\*.PDF")){
$ItemNumber = $File.Fullname -replace ".+?\\(\d{5})[^\\]*$", "`$1"
move-item -path X:\"Property Files"\05165*.pdf -destination X:\"Property Files"\"* -- $ItemNumber"
}

You could do it through the pipe if you wanted, like this:

GCI "X:\Property Files\*.PDF"|%{move-item -path X:\"Property Files"\05165*.pdf -destination X:\"Property Files"\"* -- $($_.Fullname -replace ".+?\\(\d{5})[^\\]*$", "`$1")"}

But that gets kind of long, and some people really don't like that long of a single line.

That RegEx can be tested here, plus it breaks it all down. (link to regex101.com explanation)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top