简体   繁体   中英

Powershell: Moving named files to their corresponding folder

enter image description here I have a folder which has a bunch of files named: WBF123456, WBF135464, etc. These files need to be moved to the corresponding folder. At the moment I am using the commandline to manually enter the numbers of each file so they get moved, using this code:

$files = $args[0]

mv O:\SCAN\SecSur\*$files.pdf O:\SPG\G*\*\*$files

How can I automate this process? It needs to identify the number in the filename, then move it to the folder containing the same number. Any help would be great. Thanks.

I need to get the files on the left, inside the corresponding folders on the right.

Maybe the below solution will help you. You should change $origin_path and $destination_path

    $origin_path= "C:\Users\geralexgr\Desktop\kati\files"
    $destination_path = "C:\Users\geralexgr\Desktop\kati\folders"
    Get-ChildItem $origin_path -Recurse -Include *.txt | ForEach-Object {
        $folder = [regex]::Matches($_.Name, "\d+(?!.*\d+)").value
        Move-Item $_.FullName $destination_path\$folder
    }

The example will place files under the folders that match the numeric regex.

在此处输入图像描述

After powershell execution file WBF12 gets inside 12 folder

在此处输入图像描述

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM