![移动所有仅包含单个项目的文件夹](https://linux22.com/image/684569/%E7%A7%BB%E5%8A%A8%E6%89%80%E6%9C%89%E4%BB%85%E5%8C%85%E5%90%AB%E5%8D%95%E4%B8%AA%E9%A1%B9%E7%9B%AE%E7%9A%84%E6%96%87%E4%BB%B6%E5%A4%B9.png)
我找到了一个 powershell 函数,它实际上可以满足我的需要,但不完全是......
我想找到父文件夹中仅包含一个文件的所有子文件夹。
我找到了一些可以成功找到所有正确子文件夹的代码,但现在我不太确定如何移动......
我已经创建了一个“Foreach”循环,但不太清楚如何移动……Move-Item 能做到吗?不确定
请帮忙
$RootFolder = "c:\myfolder"
$FoldersWithOnlyOneFile = Get-ChildItem $RootFolder -Recurse | `
Where {$_.PSIsContainer -and @( Get-ChildItem $_.Fullname | Where {!$_.PSIsContainer}).Length -eq 1 `
-and @( Get-ChildItem $_.Fullname | Where {$_.PSIsContainer}).Length -eq 0 }
Foreach($folder in $FoldersWithOnlyOneFile)
{
$Folder.FullName
Get-ChildItem $Folder.FullName
}
答案1
在第二个 foreach 循环中使用以下组合
$file = Get-ChildItem $Folder.FullName
move-item $file.Fullname "C:\some\where\else" # moves only the file
remove-item $folder.Fullname # remove empty source dir after file move
move-item $folder.Fullname "C:\some\where\else" # moves the folder and the file
答案2
使用以下内容作为脚本的下半部分:
$destinationRoot = "C:\some\where\else"
ForEach($folder in $FoldersWithOnlyOneFile)
{
# the folder to move to
$destinationFolder = "$destinationRoot\$($Folder.Name)"
# if it not exists, create the folder
if (!(Test-Path $destinationFolder))
{
New-Item -Path $destinationFolder -ItemType Directory
}
# move the single file (works with multiple too) to the destination
Get-ChildItem $Folder.FullName -File | Move-Item -Destination $destinationFolder
# remove the now empty original folder
Remove-Item $Folder.FullName
}