Home > Blockchain >  Powershell: Moving named files to their corresponding folder
Powershell: Moving named files to their corresponding folder

Time:09-21

enter image description here

After powershell execution file WBF12 gets inside 12 folder

enter image description here

CodePudding user response:

Apparently the files to move are .pdf files, so what you can do is get a list of those files in the source folder and then loop over that list to create (if needed) the destination subfolder and move the file there.

Try:

$destinationRoot = 'O:\SPG\G\SomeWhere'  # enter the root folder destination path here

$filesToMove = Get-ChildItem -Path 'O:\SCAN\SecSur' -Filter '*.pdf' -File
foreach ($file in $filesToMove) {
    $numName = $file.BaseName -replace '\D '  # leaving only the numbers
    # create the target path for the file
    $targetFolder = Join-Path -Path $destinationRoot -ChildPath $numName
    # create that subfolder if it does not already exist
    $null = New-Item -Path $targetFolder -ItemType Directory -Force
    # now, move the file
    $file | Move-Item -Destination $targetFolder
}
  • Related