Windows 10 Powershell code to copy files into a specific folder

q988988

New Member
I am just trying to copy the AVI files from a source folder into the corresponding destination folder based on the folder names.

For example, the multiple AVI files under Folder C should be copied into Folder xx based on the name"10Q_2P".

I guess the trick here would be the name folders (e.g.10Q_2P) that are located in different date folders, so it would require to search the names within multiple date folders to match the folder names in Destination folder, so the AVI files can be correctly copied into the corresponding folder.

Any help would be appreciated.

1583970659607.png
 
Code:
$destination_directory = "D:\Test\Destination\"

$files = Get-ChildItem -Path "D:\Test\Source" -Recurse -Filter "*.avi"



foreach ($file in $files) {

    $leaf_directory = Split-Path $file.DirectoryName -Leaf

    $target_destination = "$destination_directory$leaf_directory\xx\"

    $target_file = "$target_destination$($file.Name)"

    Move-Item -Path "$($file.Fullname)" -Destination $target_file

}

Something like that
 
Code:
$destination_directory = "D:\Test\Destination\"

$files = Get-ChildItem -Path "D:\Test\Source" -Recurse -Filter "*.avi"



foreach ($file in $files) {

    $leaf_directory = Split-Path $file.DirectoryName -Leaf

    $target_destination = "$destination_directory$leaf_directory\xx\"

    $target_file = "$target_destination$($file.Name)"

    Move-Item -Path "$($file.Fullname)" -Destination $target_file

}

Something like that
Thanks!

What if some of the AVIs are already copied into the folders? will the code overwrite the existing AVIs or just skip?
 
It would trigger a confirmation most likely. You could add a -Force to the Move-Item cmdlet to just force the move or you could add an if statement with Test-Path $file.FullName if it exists continue to the next file.
 
There are other AVI files under Folder B which should not be copied, I hope this code here will not copy them over?
 
Could you help me out with an extra line of code to exclude the items under Folder B and only copy the items in its sub folder (Folder C)?
 
To copy a folder and all its contents, use the Recurse parameter. The recursive copy will work its way through all the subfolders below the c:\test folder. PowerShell will then create a folder named test in the destination folder and copy the contents of c:\test into it
 
Back
Top