質問

私は、エンドユーザー向けの「ジャンク引き出し」である共有を持っています。必要に応じてフォルダーやサブフォルダーを作成できます。作成されてから 31 日以上経過したファイルを削除するスクリプトを実装する必要があります。

私はそれをPowershellから始めました。ファイル削除スクリプトを実行して、空になったサブフォルダーを削除する必要があります。サブフォルダーがネストされているため、ファイルが空であるが、その下にファイルを含むサブフォルダーがあるサブフォルダーは削除しないようにする必要があります。

例えば:

  • FILE3a 生後10日目です。 FILE3 生後45日目です。
  • 30 日より古いファイルを削除して構造をクリーンアップし、空のサブフォルダーを削除したいと考えています。
C:\Junk\subfolder1a\subfolder2a\FILE3a

C:\Junk\subfolder1a\subfolder2a\subfolder3a

C:\Junk\subfolder1a\subfolder2B\FILE3b

望ましい結果:

  • 消去: FILE3b, subfolder2B & subfolder3a.
  • 離れる: subfolder1a, subfolder2a, 、 そして FILE3a.

ファイルを再帰的にクリーンアップできます。サブフォルダーを削除せずにクリーンアップするにはどうすればよいですか subfolder1a?(「ジャンク」フォルダは常に残ります。)

役に立ちましたか?

解決

私は2回のパスでこれを行うだろう - 空のdirs最初の古いファイルを削除し、その後ます:

Get-ChildItem -recurse | Where {!$_.PSIsContainer -and `
$_.LastWriteTime -lt (get-date).AddDays(-31)} | Remove-Item -whatif

Get-ChildItem -recurse | Where {$_.PSIsContainer -and `
@(Get-ChildItem -Lit $_.Fullname -r | Where {!$_.PSIsContainer}).Length -eq 0} |
Remove-Item -recurse -whatif

このタイプの動作は、コマンドの第二セットが実証PowerShellでネストされたパイプラインの電力をデモ。これは、任意のディレクトリには、その下のゼロのファイルがある場合は再帰的に判断するために、ネストされたパイプラインを使用します。

他のヒント

最初の答えの精神で、ここでは空のディレクトリを削除する最短の方法は次のとおりです。

ls -recurse | where {!@(ls -force $_.fullname)} | rm -whatif
ディレクトリがの.svn

のように、フォルダが隠されていたときに

-forceフラグは例のために必要とされます

この親ディレクトリが空のネストされたディレクトリの問題を回避作業する前にサブディレクトリをソートします。

dir -Directory -Recurse |
    %{ $_.FullName} |
    sort -Descending |
    where { !@(ls -force $_) } |
    rm -WhatIf

最後のものに追加します:

while (Get-ChildItem $StartingPoint -recurse | where {!@(Get-ChildItem -force $_.fullname)} | Test-Path) {
    Get-ChildItem $StartingPoint -recurse | where {!@(Get-ChildItem -force $_.fullname)} | Remove-Item
}

これは、$始点

の下に任意の空のフォルダを削除するために検索を続ける場所、それが完了するようになります

私はいくつかの企業に優しい機能を必要としていました。ここに私のテイクがあります。

私は他の回答からコードを開始し、その後、(フォルダあたりのファイル数を含む)元のフォルダのリストをJSONファイルを追加しました。空のディレクトリを削除し、それらをログに記録します。

https://gist.github.com/yzorg/e92c5eb60e97b1d6381bする

param (
    [switch]$Clear
)

# if you want to reload a previous file list
#$stat = ConvertFrom-Json (gc dir-cleanup-filecount-by-directory.json -join "`n")

if ($Clear) { 
    $stat = @() 
} elseif ($stat.Count -ne 0 -and (-not "$($stat[0].DirPath)".StartsWith($PWD.ProviderPath))) {
    Write-Warning "Path changed, clearing cached file list."
    Read-Host -Prompt 'Press -Enter-'
    $stat = @() 
}

$lineCount = 0
if ($stat.Count -eq 0) {
    $stat = gci -Recurse -Directory | %{  # -Exclude 'Visual Studio 2013' # test in 'Documents' folder

        if (++$lineCount % 100 -eq 0) { Write-Warning "file count $lineCount" }

        New-Object psobject -Property @{ 
            DirPath=$_.FullName; 
            DirPathLength=$_.FullName.Length;
            FileCount=($_ | gci -Force -File).Count; 
            DirCount=($_ | gci -Force -Directory).Count
        }
    }
    $stat | ConvertTo-Json | Out-File dir-cleanup-filecount-by-directory.json -Verbose
}

$delelteListTxt = 'dir-cleanup-emptydirs-{0}-{1}.txt' -f ((date -f s) -replace '[-:]','' -replace 'T','_'),$env:USERNAME

$stat | 
    ? FileCount -eq 0 | 
    sort -property @{Expression="DirPathLength";Descending=$true}, @{Expression="DirPath";Descending=$false} |
    select -ExpandProperty DirPath | #-First 10 | 
    ?{ @(gci $_ -Force).Count -eq 0 } | %{
        Remove-Item $_ -Verbose # -WhatIf  # uncomment to see the first pass of folders to be cleaned**
        $_ | Out-File -Append -Encoding utf8 $delelteListTxt
        sleep 0.1
    }

# ** - The list you'll see from -WhatIf isn't a complete list because parent folders
#      might also qualify after the first level is cleaned.  The -WhatIf list will 
#      show correct breath, which is what I want to see before running the command.

30日より古いファイルを削除するには:

get-childitem -recurse |
    ? {$_.GetType() -match "FileInfo"} |
    ?{ $_.LastWriteTime -lt [datetime]::now.adddays(-30) }  |
    rm -whatif

(ただ、実際に実行に-whatifを削除します。)

とフォローアップ

 get-childitem -recurse |
     ? {$_.GetType() -match "DirectoryInfo"} |
     ?{ $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0 } |
     rm -whatif

これは私のために働いています。

$limit = (Get-Date).AddDays(-15) 

$path = "C:\Some\Path"

$limitより古いファイルの削除:

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

任意の空のディレクトリを削除するには、古いファイルを削除した後に残されます:

Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top