首页 > 解决方案 > Powershell 复杂复制并创建包含父级名称的目录

问题描述

我有一个复杂的文件夹结构要移动

我有一个包含 2000 个文件的文件夹,这些文件必须以新的文件结构移动,我用 powershell 做了一些简单的任务,但不是那么复杂,所以我完全迷失了......没有找到其他问题的任何解决方案......

所有包含 23 个文件的文件夹(一些 .dds 一些 .xml 等等)文件夹必须完全移动

这是实际情况:

文件\128891\
文件\128986\
文件\129362\
文件...\

必须移动到:

文件\128891\aaa\bbb\ccc\ddd\eee\real\128891\
文件\128986\aaa\bbb\ccc\ddd\eee\real\128986\
文件\129362\aaa\bbb\ccc\ddd\eee\真实\129362\
文件...\aaa\bbb\ccc\ddd\eee\真实...\

文件中有大约 2000 个文件夹,这些文件夹必须与它们的文件一起移动

非常感谢您的帮助

标签: powershellrobocopy

解决方案


您可以修改我的代码(不是更好的方法,但可以)

 $foldernames=Get-ChildItem -Recurse "D:\testdir" | ?{ $_.PSIsContainer } #get all folder in start folder, for you must be "...files\"
    foreach($foldername in $foldernames){
    $files=Get-ChildItem -Path $foldername.FullName|Where-Object {! $_.PSIsContainer} #get all files in current folder, no recurse,no subfolders.
    $files|Move-Item -Destination (New-Item -ItemType Directory -Path (Join-Path -path $foldername.FullName  -ChildPath ("aaa\bbb\ccc\ddd\eee\real\"+$foldername.Name)) -Force)
    #move all files and create directories
    }

额外的:

如果你有文件夹,子文件夹,你必须修复这样的代码

$foldernames=Get-ChildItem "D:\testdir"  | ?{ $_.PSIsContainer } 
foreach($foldername in $foldernames){
$files=Get-ChildItem -Path $foldername.FullName
$files|Move-Item -Destination (New-Item -ItemType Directory -Path (Join-Path -path $foldername.FullName  -ChildPath ("aaa\bbb\ccc\ddd\eee\real\"+$foldername.Name)) -Force)
}

它从文件夹 128891(一个例子)中全部移出,包括子文件夹

如果您在文件夹中有子文件夹,但您只想从中移动文件,则必须像这样进行文件处理:

$files=Get-ChildItem -Path $foldername.FullName -recurse|Where-Object {! $_.PSIsContainer}

但请记住,在这种情况下,由于文件名重复,可能会发生错误


推荐阅读