peterbonar
peterbonar

Reputation: 599

Move Files From One Location To Another And Exclude Subfolders

I want to move files from one location to another but not to move any files from subfolders in the directory I'm moving the files from.

I have the following code but this moves files in subfolders. Also, the extensions should only be .xml and .pdf.

This script moves all files from $MoveThese into the Destination, even the files in subfolders e.g. C:\Test\Folder1\Subfolder. Any suggestions would be helpful.

$MoveThese = "C:\Test\Folder1", "C:\Test2\Folder2", "C:\Test3\Folder3"
$Destination = "C:\Test\Docs", "C:\Test2\Docs", "C:\Test3\Docs"

For($i=0; $i -lt $FailFolders.Length; $i++){
Get-ChildItem -Path $MoveThese[$i] -Recurse -Include "*.xml", "*.pdf" | Move-Item -Destination $Destination[$i] 
}

Upvotes: 0

Views: 1820

Answers (2)

Theo
Theo

Reputation: 61038

Include does not work without the -Recurse switch unfortunately unless the path uses a wildcard like in C:\Windows*

This might do it for you:

$MoveThese = "C:\Test\Folder1", "C:\Test2\Folder2", "C:\Test3\Folder3"
$Destination = "C:\Test\Docs", "C:\Test2\Docs", "C:\Test3\Docs"

For($i=0; $i -lt $MoveThese.Length; $i++){
  Get-ChildItem  $MoveThese[$i] -File | 
    Where-Object { $_.Name -like "*.xml" -or $_.Name -like "*.pdf" | 
    Move-Item -Destination $Destination[$i] -Force
}

Upvotes: 0

G42
G42

Reputation: 10019

If you don't want files in subfolders, don't use -Recurse. As per Get-ChildItem documentation this "Gets the items in the specified locations and in all child items of the locations."


Missed this part of the -Include statement:

The -Include parameter is effective only when the command includes the -Recurse parameter

Solution:

Get-ChildItem  $MoveThese[$i] -File |
    Where-Object {$_.Extension -in @(".xml",".pdf")} |
    Move-Item -Destination $Destination[$i]

Upvotes: 3

Related Questions