EN VI

Powershell- Move files to destination folder based on prefix matching?

2024-03-12 00:00:11
How to Powershell- Move files to destination folder based on prefix matching

I have a series of documents that all begin with their file number (File number is always 6 characters):

A12345_Letter.pdf

A12346_Email.pdf

I need to move them to the appropriate subfolder in their file. Each file will only have one destination folder, but sometimes the folder name contains additional characters:

C:\Directory\Destination\A12345\Corres C:\Directory\Destination\A12346 - KlA69 LJ236\Corres

There may be numbers or letters, there may or may not be a space after the file number- there is no pattern or set number of characters.

This is what I've come up with:

$sourceDirectory = "C:\Directory\Source"
$files = Get-ChildItem -File -Path $sourceDirectory
$destination = "C:\Directory\Destination"
$filesDictionary = @{}
foreach ($file in $files) {
$prefix = $file.Name.Substring(0, 6)
$folderPath = Join-Path -Path $destination -ChildPath $prefix | Join-Path -ChildPath "Correspondence" 
 $destinationPath = Join-Path -Path $folderPath -ChildPath $file.Name
    Move-Item -Path $file.FullName -Destination $destinationPath
}

(At this time I do not want to create a destination folder if one doesn't exist)

This works for scenarios where the name of the destination folder is just the 6-character file number, but not scenarios where there are additional characters in the destination folder name.

I'm trying to edit my $folderPath line so the first -Childpath starts with $prefix. I am just teaching myself Powershell in my spare time; I've done some reading about StartsWith, but I can't figure out how to make it work in this Join-Path scenario.

Solution:

Note: this is based on the presumption there will not be more than 1 Destination Directory with the same 6-characters prefix

$SourceDirectory = 'C:\Directory\Source'
$DestinationDirectory = 'C:\Directory\Destination'

$FileList = Get-ChildItem -File -Path $sourceDirectory

foreach ($file in $FileList) {


    $prefix = $file.BaseName.Substring(0, 6)


    # this works ONLY if there is JUST ONE matching directory
    $FinalDestination = Join-Path -Path (Get-ChildItem -Directory -Filter "$prefix*" -Path $DestinationDirectory) -ChildPath 'Correspondence'

    # No need to put the full name in the destination unless you want to RENAME the file while moving it, as long as you are moving a File into a Directory
    Move-Item -Path $file.FullName -Destination $FinalDestination
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login