Powershell 找早於15天的檔案

這個需求在 linux 用 find 寫,很方便

find /tmp/location -type f -mtime +15 -delete

在 Windows Powershell 的話,可以參考這篇 Delete files older than 15 days using PowerShell

$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

這是使用 Get-ChildItem -Path $path ,搭配 Where-Object ,Where-Object 裏面是做判斷, $_ 是每個項目,用每個項目的 CreationTime 去判斷,然後用 Remove-Item 去刪除。

找指定位置下的目錄

想找到指定位置下的目錄,但不要再深入。指定位置下的目錄是這樣的

/tmp/location
  +-- dir1
    + dir11
  +-- dir2
    + dir21
  foo.txt

我預期是只看到 dir1 跟 dir2,所以我用 find

find /tmp/location -type d -print

結果我找到的是

/tmp/location
/tmp/location/dir2
/tmp/location/dir2/dir21
/tmp/location/dir1
/tmp/location/dir1/dir11

find 的輸出跟我預期的不相符啊,我又不想用 ls 處理,後來找到 -maxdepth -mindepth 這兩個參數,搭配起來使用就可以了。

find /tmp/location -maxdepth 1 -mindepth 1 -type d -print

這樣就會是我需要的 dir1 跟 dir2

/tmp/location/dir2
/tmp/location/dir1

又學到一課,謝謝你 find