Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 删除特定子文件夹为空的父文件夹_Powershell - Fatal编程技术网

Powershell 删除特定子文件夹为空的父文件夹

Powershell 删除特定子文件夹为空的父文件夹,powershell,Powershell,我有多个已定义子文件夹结构的父文件夹: C:\parent1\Sub1 C:\parent1\Sub2 C:\parent1\ C:\parent2\Sub1 C:\parent2\Sub2 C:\parent2\ 我需要删除名为“Sub2”的子文件夹为空的所有父文件夹。此代码将完全执行此操作。$path变量包含父文件夹所在的位置 $path = 'C:\' $parentfolders = Get-Childitem $path -Directory foreach ($parentfo

我有多个已定义子文件夹结构的父文件夹:

  • C:\parent1\Sub1
  • C:\parent1\Sub2
  • C:\parent1\
  • C:\parent2\Sub1
  • C:\parent2\Sub2
  • C:\parent2\

我需要删除名为“Sub2”的子文件夹为空的所有父文件夹。

此代码将完全执行此操作。$path变量包含父文件夹所在的位置

$path = 'C:\'
$parentfolders = Get-Childitem $path -Directory 
foreach ($parentfolder in $parentfolders){
    foreach ($childfolder in (Get-Childitem $($parentfolder.FullName) -Directory )){
        if ($childfolder.Name -eq "Sub2"){
            if((Get-Childitem $($childfolder.FullName) | Measure-Object).Count -ne 0){
                Remove-Item -Path $($parentfolder.FullName) -Force -Recurse
            }
        }
    }
}
编辑: 我把我的答案和戴夫·塞克斯顿的答案结合起来

$path = 'C:\'
    $parentfolders = Get-Childitem $path 
    foreach ($parentfolder in $parentfolders){
        Get-ChildItem -Filter Sub* -Recurse | ? {(Get-ChildItem -Path $_.FullName).Count -eq 0} | % {Remove-Item $_.Parent -Recurse} 

    }

假设您在根文件夹中:

Get-ChildItem -Filter Sub* -Recurse | ? {((Get-ChildItem -Path $_.FullName).Count -eq 0) -and $_.Name -eq 'Sub2'} | % {Remove-Item $_.Parent -Recurse} 

请告诉我们你自己试过什么。堆栈溢出不是代码编写服务。是否所有父文件夹都位于C:\的根目录下?您应该自己用代码尝试此操作,并向我们提供卡住的位置。这仅适用于一个文件夹,他有多个父文件夹无法理解您的注释-这将删除多个父文件夹。如果不指定
-Directory
,则
Get-ChildItem
cmdlet还会返回FileInfo对象。因为所有这些你的梦想都将失败。另外,为什么要在所有文件夹都有一个公共根目录的情况下使用3次Get Childitem?