2020 年 9 月 16 日

IT Skills 波林

Polin WEI – 資訊工作者的技術手札

powershell delete folders and files

1 min read
del_folders_files

使用 powershell 刪除目錄及檔案 ( delete folders and files )

 

Powershell 是微軟公司開發的任務自動化和組態管理框架,由.NET Framework和.NET Core是構建的命令行介面殼層相關手稿語言組成,Powershell Cmdlet 是設計來處理物件。若有定時要刪除特定目錄下所有檔案及目錄時,可以使用下列的 Powershell Script.

檔案名: del_folder_file.ps1

$rootFolder = "d:\ps"
$excludeFolder = "D:\ps\public"

#處理根目錄下所有目錄
$folders = Get-ChildItem $rootFolder -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName
ForEach ($folder in $folders) {
    if ($folder.FullName -ne $excludeFolder){
        $exisits = Test-Path $folder.FullName
        If ($exisits ) { 
            Write-Host "It is going to delete folder:"  $folder.FullName 
            Write-Output "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - It is going to delete folder:  $folder" | Out-File -FilePath  "D:\tmp\pslog.txt" -append
            Get-ChildItem -Path $folder.FullName -Include *.* -File -Recurse | foreach { $_.Delete()}
            Remove-Item $folder.FullName -Recurse -Force -Confirm:$false
        }        
 }
      
}

#處理根目錄下所有檔案
$files = Get-ChildItem $rootFolder | Select-Object FullName
ForEach ($file in $files) {
    if ($file.FullName -ne $excludeFolder){
        $exisits = Test-Path $file.FullName
        If ($exisits ) {
            Write-Host "It is going to delete file:"  $file.FullName
            Write-Output "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - It is going to delete file:  $file" | Out-File -FilePath  "D:\tmp\pslog.txt" -append          
            Remove-Item $file.FullName -Recurse -Force -Confirm:$false
        }      
    }      
}

del_folders_files

 

  1. Get-ChildItem : 用來取得目錄下所有檔案及目錄清單
  2. if statement : 用來判斷條件,在這個範例是用來排除 public 目錄 ( -eq for equality , -ne not equal )
  3. Write-Host : 用來在螢幕顯示執行狀況
  4. Write-Output : 用來將執行狀況寫在檔案裡
  5. $(Get-Date -Format ‘yyyy-MM-dd HH:mm:ss’) : 取得現行時間
  6. Out-File : 將訊息輸出到檔案

 

More Stories

Copyright © All rights reserved. | Newsphere by AF themes.