将文件从子文件夹移动到父文件夹Windows 10 cmd powershell

问题描述 投票:0回答:1

我一直在尝试通过运行以下 .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

文件夹。上面的代码将文件移动到脚本所在的当前文件夹或父文件夹(从脚本位置向上),具体取决于通配符“..”或“.”

任何想法/想法将不胜感激。

powershell file move
1个回答
0
投票

解决方案由@francishagyard2 here

提供

根路径通过变量 $PSScriptRoot 引用脚本的位置。这就是我在大多数情况下使用的方式。

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

© www.soinside.com 2019 - 2024. All rights reserved.