Long
Long

Reputation: 15

How to using "Get-ChildItem" and "ForEach" loop all folder in Powershell?

I have a folder named "Folder-Test". In the "Folder-Test" folder there are 3 sub-folders: "A", "B-1", "C-1".

How do I use "Get-ChildItem" to get a list of folders containing "-" in the name ("B-1", "C-1"). Then, use "ForEach-Object" and "Copy-Item" to copy the folders containing "-" in the name ("B-1", "C-1") to another folder.

My old code:

$path = (gci "D:\Folder-All" -Filter "Folder-Test" -Recurse).FullName
mkdir "D:\Another-Folder"
Get-ChildItem $path -Directory |
ForEach-Object {if (($_.enumeratefiles() | measure).count -gt 0)
{Copy-Item $path "D:\Another-Folder" -Filter {PSIsContainer} -Recurse -Force}
               }

Upvotes: 0

Views: 4971

Answers (1)

Jason Boyd
Jason Boyd

Reputation: 7029

This gets all directories in "D:\Folder-All\Folder-Test" that contain a dash in the name and recursively copies them to "D:\Another-Folder".

Get-ChildItem -Path "D:\Folder-All\Folder-Test\*-*" -Directory | 
Copy-Item -Destination "D:\Another-Folder" -Recurse

Upvotes: 1

Related Questions