PowerShell 删除最后一个子文件夹

PowerShell remove last sub folder

有没有办法使用 PowerShell 只删除最后一个空文件夹?
示例:我有一个文件夹结构

..-mainFolder
.....................-子文件夹 1
................................................- 一个
................................................- b
................................................- c
.................-子文件夹 2
................................................- 一个
.....................................- b

每天晚上我都会使用 robocopy 将所有内容复制到另一台服务器,后记我应该删除所有最后的子文件夹(a、b、c 等..)。

使用 /MUVE 它会删除“subFolder1”和“subFolder2”,但它们应该保留在那里
(如果我删除文件夹 "a"、"b"、"c","subFolder1" 也是空的,所以我无法删除所有空文件夹。)

我不能使用 /FX,我不知道文件夹的名称,只知道根目录路径
"C:\SharedFolders\"。我知道应该删除的文件夹在第 3 级。

您可以使用 Get-ChildItem cmdlet with the -Directory switch to retrieve all folders, filter the empty folders using the Test-Path cmdlet and finally delete the folders using Remove-Item:

Get-ChildItem 'C:\SharedFolders' -Directory -Recurse | 
  where { -not (Test-Path (Join-Path $_.FullName '*')) } | 
  Remove-Item

这将仅删除最后一个空文件夹,结果:

..-mainFolder 
...................-subFolder1 
..................-subFolder2 

您可以使用 Get-ChildItem -Recurse 检索所有文件夹,然后在目录对象上调用 GetFiles()GetDirectories() 方法来确定它们是否为空:

$EmptyDirs = Get-ChildItem C:\path\to\mailFolder -Directory -Recurse | Where {-not $_.GetFiles() -and -not $_.GetDirectories()}
# and then remove those
$EmptyDirs | Remove-Item