我找到了一个 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
}