iT邦幫忙

0

powershell 移除過期檔案但保留某些資料夾

  • 分享至 

  • twitterImage

各位好
我現在要用powershell移除掉一個目錄裡面超過30天未使用的檔案及資料夾
但是需要保留幾個子目錄及底下的檔案

|-C:\TEST
-C:\TEST\A
-C:\TEST\A\A1
-C:\TEST\A\A2.txt
-C:\TEST\B
-C:\TEST\B\B1
-C:\TEST\B\B2.txt
-C:\TEST\C
-C:\TEST\C\C1
-C:\TEST\C\C2.txt
-C:\TEST\D.doc
-C:\TEST\E.txt

除了A跟B資料夾外的檔案,超過30天未使用必須刪除
我嘗試了exclude跟.Fullname -notlike都沒有成功
請教一下各位該怎麼寫?
謝謝

#notlike
$before=(Get-Date).AddDays(-30) $exfolder=('C:\TEST\A*' , 'C:\TEST\B*')
Get-ChildItem -path 'C:\TEST' -Recurse
Where-Object {($.LastWriteTime -lt $before ) -and ( $.FullName -notlike
$exfolder)} |
Remove-Item -force -Recurse

#exclude
$before=(Get-Date).AddDays(-30)
$exfolder=('C:\TEST\A*' , 'C:\TEST\B*' )
Get-ChildItem -path 'C:\TEST' -Recurse -Exclude $exfolder
Where-Object { $_.LastWriteTime -lt $before } |
Remove-Item -force -Recurse

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
zero
iT邦好手 1 級 ‧ 2018-09-27 15:43:03

抱歉,這是哪邊弄來的範例嗎?? 還是這邊發文會把程式碼弄亂?

Where-Object前面沒有目標可以找,你錯誤訊息要不要貼上來?

就算程式碼是同一行因為這邊編輯文章導致被換行了,也沒看到你的連續執行符號,

然後也沒看到串接引號, Where-Object{}裡面要用到物件變數要用 $_.

你直接打$.LastWriteTime 找不到變數的資料的

程式邏輯沒錯,但是感覺反而犯了一些怪怪的基本錯誤

我要發表回答

立即登入回答