我一直在尝试通过运行以下 .bat 和 .ps1 脚本将文件从多个子文件夹移动到其父文件夹:
1. forfiles /s /m *.* /c "cmd /c move @path %CD%"
2. powershell -Command "gci *.* -R | mv -D ."
3. Get-ChildItem -File -Recurse | Move-Item -Destination .
4. Get-ChildItem -File -Recurse | Move-Item -Destination ..
文件夹结构为“顶级文件夹”和两个子文件夹:Top_folder\Subfolder_1\Subfolder_2。目的是从主“顶级文件夹”运行脚本,并将 Subfolder_2 中的所有文件移至 Subfolder_1。主文件夹有很多
Subfolder_1\Subfolder_2
Subfolder_1\Subfolder_2
...
Subfolder_1\Subfolder_2
文件夹。上面的代码将文件移动到脚本所在的当前文件夹或父文件夹(从脚本位置向上),具体取决于通配符“..”或“.”
任何想法/想法将不胜感激。
解决方案由@francishagyard2 here
提供
$RootPath = $PSScriptRoot
$ParentFolders = Get-ChildItem -Path $RootPath |其中{$_.PSIsContainer}
ForEach($ParentFolders 中的 $Parent){ Get-ChildItem -路径 $Parent.FullName -Recurse |其中 {!$.PSIsContainer -and ($.DirectoryName -ne $Parent.FullName)} |对于每个{ $文件公司 = 1 做 { If ($FileInc -eq 1) {$MovePath = Join-Path -Path $Parent.FullName -ChildPath $.Name} 否则 {$MovePath = Join-Path -Path $Parent.FullName -ChildPath "$($.BaseName)($FileInc)$($.Extension)"} $文件公司++ } while (测试路径 -Path $MovePath -PathType Leaf) 移动项目 -Path $.FullName -Destination $MovePath } }