用于递归删除的 Powershell 脚本

用于递归删除的 Powershell 脚本

我已经开始了一份新工作,并且几乎立即被要求做一些 Powershell,但是我只在 Exchange 中使用过 Powershell,而且只是非常基础的。

我将在接下来的几个月里进行更多的学习,但现在,我需要一个脚本,它可以进入任意文件夹,递归检查每个文件夹和子文件夹,删除任何超过 2 天的文件。

有人能帮助新手解决这个问题吗?'

Function DelFiles($RootFolder,[ref]$blnDeleteErrmsgSent){
  $blnDeleteErrmsgSent  = $false
  $date                 = Get-Date
  $Folders              = Dir
  $FolderPath           = "path"
  $PSEmailServer        = "servername"

  # Delete Old Files
  Cd $RootFolder

  foreach($folder in $Folders){
    Cd $Folder.FullName
    $ToDelete = Dir -Attributes !readonly |Where {$_.lastwritetime -lt ((Get-Date).Adddays(-2))}
    foreach($File in $ToDelete){
      try{
        if($file.Attributes -notcontains "Directory"){
        Remove-Item -Path $File.FullName -Force -ErrorAction Stop}
      }catch{
        # Only Send e-mail alert if we haven't already done so i.e. only once
        if(!($blnDeleteErrmsgSent.value)){
          $errordescription=$_
          $errorline=$_.InvocationInfo.Line.ToString()

          # Capture Error Information
            # Notify IT that this script has encountered an error
            Send-MailMessage -From "ScanDeletion@****.co.uk" -To "IT@****.co.uk" -Subject "errored while deleting old scan files" -Body ("The error occured at " + [string]$date +"`n Error:"+ $errordescription +"`n Line:"+ $errorline)

            # Set Flag to True so we don't send multiple e-mail alerts for file deletion errors.
            $blnDeleteErrmsgSent.value = $true
        }
      }
    }
  }
}

# Call Archive Function (auto-recursive) to archive any xml files in Folder, and subfolders
DelFiles $FolderPath ([ref]$blnDeleteErrmsgSent)

Exit

答案1

我想你离得并不远,但以下是我会做不同的事情:

  • 使用 开关,只需一个命令即可获取所有文件-RecurseGet-ChildItem而不必从一个文件夹跳到另一个文件夹以获取其中的文件
  • 不要为电子邮件创建标志,而是收集要在删除过程中发送的信息,将它们存储在数组中,然后发送一次电子邮件
  • 不要检查要删除的文件是否不是文件夹,而是使用-File以下参数Get-ChildItem

我也会将其用作脚本,而不是Function,但那是你的选择:

$RootFolder = "C:\install\su1587308"
$DeleteDate = (Get-Date).AddDays("-2")
$Fails      = @()

# Get all files below the rootfolder that are not ReadOnly:
Get-ChildItem $RootFolder -Recurse -Attributes !ReadOnly -File |
  Where-Object { $_.LastWriteTime -lt $DeleteDate } | ForEach-Object {
    Try {
      Remove-Item $_.FullName -Force -ErrorAction Stop
    } Catch {
      # if it fails to the delete, the fullname of the file is stored in a variable
      $Fails += $_.FullName
    }
  }

# Only send an email if something failed:
if ($Fails) {
  $Body = "Could not delete the Following Files:<br>" +($Fails -join '<br>')
  $Splat = @{
    SmtpServer = "???"
    From       = "ScanDeletion@****.co.uk"
    To         = "IT@****.co.uk"
    Subject    = "errored while deleting old scan files"
    Body       = $Body
    BodyAsHtml = $true
  }

  Send-MailMessage @Splat
}

相关内容