首页 > 解决方案 > 如何在 Powershell 中使用“Get-ChildItem”和“ForEach”循环所有文件夹?

问题描述

我有一个名为“文件夹测试”的文件夹。在“Folder-Test”文件夹中有 3 个子文件夹:“A”、“B-1”、“C-1”。

如何使用“Get-ChildItem”获取名称中包含“-”的文件夹列表(“B-1”、“C-1”)。然后,使用“ForEach-Object”和“Copy-Item”将名称中包含“-”的文件夹(“B-1”、“C-1”)复制到另一个文件夹。

我的旧代码:

$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}
               }

标签: powershell

解决方案


这将获取“D:\Folder-All\Folder-Test”中名称中包含破折号的所有目录,并将它们递归地复制到“D:\Another-Folder”。

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

推荐阅读