我一直在尝试通过运行以下 .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
提供
# Root path is referenced to script's location by means of variable $PSScriptRoot. That's how I use ones in most cases.
$RootPath = $PSScriptRoot
# Get list of parent folders in root path
$ParentFolders = Get-ChildItem -Path $RootPath | Where {$_.PSIsContainer}
# For each parent folder get all files recursively and move to parent, append number to file to avoid collisions
ForEach ($Parent in $ParentFolders) {
Get-ChildItem -Path $Parent.FullName -Recurse | Where {!$_.PSIsContainer -and ($_.DirectoryName -ne $Parent.FullName)} | ForEach {
$FileInc = 1
Do {
If ($FileInc -eq 1) {$MovePath = Join-Path -Path $Parent.FullName -ChildPath $_.Name}
Else {$MovePath = Join-Path -Path $Parent.FullName -ChildPath "$($_.BaseName)($FileInc)$($_.Extension)"}
$FileInc++
}
While (Test-Path -Path $MovePath -PathType Leaf)
Move-Item -Path $_.FullName -Destination $MovePath
}
}