powershell 删除IIS日志

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 删除IIS日志相关的知识,希望对你有一定的参考价值。

function Clean-Logs {
<#
  .SYNOPSIS
  Remove files oder than x days from x location
  .DESCRIPTION
  Mainly used to remove IIS logs that are older than a certain number of days.
  .EXAMPLE
  Clean-Logs -Retention 7 -Directory D:\Logs
  .PARAMETER Retention
  Number of days to retain logs. Specifying 7 will remove logs older than 7 days.
  .PARAMETER Directory
  The path to the target log directory. The cmdlet will default to C:\inetpub\logs\LogFiles.
#>

    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$True,
        HelpMessage='Specify your desired retention period and log location')]
        [int]$Retention,
        [string]$Directory = 'C:\inetpub\logs\LogFiles',
        [switch]$ShowOnly
    )
    
    begin {

    	$now = Get-Date
	$extension = "*.log"
	$lastWrite = $Now.AddDays(-$retention)
	$files = Get-ChildItem $Directory -Include $extension -Recurse | ? {$_.LastWriteTime -le $lastWrite}

        Write-Verbose -Message " - Current time: $now"
        Write-Verbose -Message " - Last write time: $lastWrite"
        Write-Verbose -Message " - Retention days: $Retention"        
        Write-Verbose -Message " - File extension: $extension"
        Write-Verbose -Message " - Number of files $($files.count)"

    }

    process {
	if (!$ShowOnly){
		$files | ForEach-Object {

            		if ($_ -ne $NULL) {

				Remove-Item $_.FullName | Out-Null
            		}
        	}
    	}
    }
    	

    end{}

}

#Run from a scheduled task with %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -noprofile D:\Scripts\Delete-IISLogs.ps1
#Remove -ShowOnly to delete logs
Clean-Logs  -Retention 7 -Directory 'C:\inetpub\logs\LogFiles' -ShowOnly -Verbose

以上是关于powershell 删除IIS日志的主要内容,如果未能解决你的问题,请参考以下文章

PowerShell脚本,每隔10分钟监视IIS日志500个错误

定期删除IIS日志文件

通过 Powershell 在远程机器上更改 IIS 网站的物理路径

powershell 删除旧日志

powershell 删除8天前的日志

定期删除IIS日志文件