Removing Old Exchange 2013/2016 Log Files


Update: 18th Sept 2014. An updated version of this script has been written by Thomas Stensitzki and can be downloaded from http://www.sf-tools.net/Messaging/tabid/55/EntryId/213/Updated-script-to-purge-Exchange-and-IIS-log-files.aspx. This updated version works on systems that have not used the default installation paths and it reads them automatically from the server. The below still works for users with default installation paths.

Exchange 2013 creates log files for everything, and this is way more than in 2010. Everything is logged, and even when the server is doing nothing, it is recording the health of the server and writing that down to the logs.
The following PowerShell script removes log files (those named *.log) over 30 days old in the IIS logs folder and the same from the Exchange 2013 logging folder. Neither of these folders are cleaned up automatically in Exchange 2013 RTM or SP1. The transport logs in a different folder are cleaned up automatically after 30 days, so this script uses the same duration.

Set-Executionpolicy RemoteSigned -Force
$days=30 #You can change the number of days here

$IISLogPath="C:\inetpub\logs\LogFiles\"
$ExchangeLoggingPath="C:\Program Files\Microsoft\Exchange Server\V15\Logging\"
$WindowsTemp="C:\Windows\Temp\"

Write-Host "Removing IIS, TMP_ and Exchange logs; keeping last" $days "days"
Function CleanTmpFiles($TargetFolder)
{
    Write-Host "Deleting tmp_* files and folders in $TargetFolder" 
    Get-ChildItem $TargetFolder -Include tmp_* -Recurse -ErrorAction SilentlyContinue | foreach ($_) {Remove-Item $_.FullName -Recurse -ErrorAction SilentlyContinue}
}
Function CleanLogfiles($TargetFolder)
{
    if (Test-Path $TargetFolder) {
        $Now = Get-Date
        $LastWrite = $Now.AddDays(-$days)
        $Files = Get-ChildItem $TargetFolder -Include *.log -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
        foreach ($File in $Files)
            {Write-Host "Deleting file $File" -ForegroundColor "Red"; Remove-Item $File -ErrorAction SilentlyContinue | out-null}
       }
Else {
    Write-Host "The folder $TargetFolder doesn't exist! Check the folder path!" -ForegroundColor "red"
    }
}

CleanLogfiles($IISLogPath)
CleanLogfiles($ExchangeLoggingPath)
CleanTmpFiles($WindowsTemp)

The above script runs in PowerShell and will delete logs on the server that you are running the script on.

The following version of the same script will get all the Exchange 2013 or later servers in the organization (excluding Edge Role servers) and then deletes the logs (older than 30 days) across all the servers for you from one machine. You run this second script from Exchange Management Shell (run as administrator) and need remote file access to C$ (or whichever folder you set in the script) to all the servers Exchange 2013 servers.

Set-Executionpolicy RemoteSigned -Force
$days=30 #You can change the number of days here

$ExchangeInstallRoot = "C"
$IISLogPath="inetpub\logs\LogFiles\"
$ExchangeLoggingPath="Program Files\Microsoft\Exchange Server\V15\Logging\"
$WindowsTemp="Windows\Temp\"


Write-Host "Removing IIS and Exchange logs; keeping last" $days "days"
Function CleanTmpFiles($TargetFolder)
{
    $TargetServerFolder = "\\$E15Server\$ExchangeInstallRoot$\$TargetFolder"
    Write-Host "Deleting tmp_* files and folders in $TargetServerFolder"
    Get-ChildItem $TargetServerFolder -Include tmp_* -Recurse -ErrorAction SilentlyContinue | foreach ($_) {Remove-Item $_.FullName -Recurse -ErrorAction SilentlyContinue}
}
Function CleanLogfiles($TargetFolder)
{
    $TargetServerFolder = "\\$E15Server\$ExchangeInstallRoot$\$TargetFolder"
    Write-Host $TargetServerFolder
    if (Test-Path $TargetServerFolder) {
        $Now = Get-Date
        $LastWrite = $Now.AddDays(-$days)
        $Files = Get-ChildItem $TargetServerFolder -Include *.log -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
        foreach ($File in $Files)
            {
               # Write-Host "Deleting file $File" -ForegroundColor "Red"
                Remove-Item $File -ErrorAction SilentlyContinue | out-null}
        }
Else {
    Write-Host "The folder $TargetServerFolder doesn't exist! Check the folder path!" -ForegroundColor "red"
    }
}

$Ex2013 = Get-ExchangeServer | Where {($_.IsE15OrLater -eq $true) -and ($_.ServerRole -ne "Edge")}

foreach ($E15Server In $Ex2013) {
    CleanLogfiles($IISLogPath)
    CleanLogfiles($ExchangeLoggingPath)
    CleanTmpFiles($WindowsTemp)
    }


Posted

in

, , ,

by

Tags:

Comments

25 responses to “Removing Old Exchange 2013/2016 Log Files”

  1. Anonymous avatar
    Anonymous

    So what if you install Exchange bits using non-default path? 🙂

  2. Brian Reid avatar

    @Anon – you “tweak” the script

  3. TS avatar

    Or you can use:
    $ExchangeLoggingPath=(Get-ItemProperty “HKLM:\SOFTWARE\Microsoft\ExchangeServer\v15\Setup\”).MsiInstallPath + “Logging\”

  4. TS avatar

    Or use:
    $ExchangeLoggingPath=(Get-ItemProperty “HKLM:\SOFTWARE\Microsoft\ExchangeServer\v15\Setup\”).MsiInstallPath + “Logging\”

  5. Brian Reid avatar

    @TS – or just use $env:ExchangeInstallPath, but that does not get the IIS log path.

  6. movi sajid avatar
    movi sajid

    Hi,
    thanks for the script, can you pleas send me the method to run this script, as i am new and unable to run it. also please send me the .ps1 of this script,
    thanks in advance.
    Regards
    movi

    movisajid@gmail.com

    1. Brian Reid avatar

      PS1 scripts are just the PowerShell script as a text file with .ps1 as the extension (and not .txt). You run then in the PowerShell window (or in the case of the second of these scripts, from the Exchange Management Shell windows as it uses Exchange PowerShell extensions). To run in PowerShell change directory to the folder the script is in (“cd c:\scripts” for example) and then execute the script (“.\Remove-ExchangeLogFiles.ps1” for example). You do not need a PS1 download as you just copy the text on the screen into Notepad and save it as a PS1.

  7. yashvardhan avatar
    yashvardhan

    Hi brian

    just want to know , if i will RUN this script. I hope it will not affect my running production environment.

    pl confirm because for my environment also C: drive getting full.

    1. Brian Reid avatar

      It will not impact your environment. It just removes log files. If you want to test it in a lab enviromnent – please do, and if you backup the log folders for the first few times you run it, please feel free to do so.

      1. yashvardhan avatar
        yashvardhan

        thanks for your input , I have tried this in my production environment without any problem. its works fine.

  8. Jason avatar
    Jason

    Thank you for this, it ran perfectly and reclaimed GBs of space in my VM environment! Thanks much!

    Jason

  9. […] vigorous that you’ll often find it taking up quite a bit of your disk space. Luckily there are methods to truncate unneeded logs. These logs have come in handy when I’ve had to troubleshoot odd issues in the past related to […]

  10. […] Removing Old Exchange 2013 Log Files (by Brian Reid) […]

  11. Lee avatar
    Lee

    Hi Brian

    Thanks for the scripts. I used the first script on my development instance and it cleared out 20 GB of log files and brought Exchange online again. I’ve now set this up to run as a daily task.

    Kind regards,

    Lee

  12. jackr avatar
    jackr

    Why does not MS auto clear log files? that make such terrible software.

    1. Brian Reid avatar

      Becuase data is important. If you take your log files and store them in a big data processing ssytem then you can make observations from this data that you otherwise would not have. If you are not going to do this, then fine – delete the logs. But it would be remise of Microsoft to delete logs that might contain useful information to your enterprise.

      For example, imagine getting reports that the latest version of some mobile OS is causing a problem. Did it happen last week or last month with the previous version? How would you know if you did not have the ability to see the history of your service to your users.

  13. Jason Sherry avatar

    The method I use is a one line Scheduled Task using FORFILES CLI.

    1) Create a daily scheduled task with the following
    2) Action: Start a program
    3) Program: FORFILES
    4) Arguments: /p “C:\Program Files\Microsoft\Exchange Server\V15\Logging” /s /m *.* /c “cmd /c Del @path” /d -7

    Change the path above to where your E15 Logging folder is. Change the “-7” to control how many days to keep, “-7” = 7 days.

    Create a 2nd Task to delete IIS logs, by default in “C:\inetpub\logs\LogFiles”

  14. Jason Sherry avatar

    Just created a blog post on using FORFILES, included with Windows Vista and higher, here: http://blog.jasonsherry.net/2014/12/11/remove-older-exchange-2013-and-iis-log-files-with-this-one-liner/

  15. […] Brian’s blog | Thomas’ blog | TechNet Script Gallery […]

  16. […] Check to see that your hard disks aren’t full. Exchange loves to log everything, even more so with 2013. If your logs are on a separate volume, check this – there are some handy scripts out there that can clean these out for you – http://c7solutions.com/2013/04/removing-old-exchange-2013-log-files-html […]

  17. Ciro avatar
    Ciro

    Thanks, it’s very helpful!

  18. Pete Hartman avatar
    Pete Hartman

    We had an issue with the exchange diagnostic logs filling up the C drive. Put in task scheduler a script to delete the files daily. Initially worked, until we put a GPO in place restricting access to powershell. Then the C: drive started filling back up again. Running the script in task scheduler said completed, but didn’t delete anything. Right clicked the script, open as administrator, and immediately was greeted with a warning that a policy was in place to prevent scripts running, and would I like to modify the policy? I chose yes, and then after 10 seconds or so, the powershell screen was filled with confirmation that files were being deleted.

    1. Brian Reid avatar

      @pete. Do you find you break other stuff by restrictions on PowerShell on the Exchange Servers?

  19. […] Brian’s blog | Thomas’ blog | TechNet Script Gallery […]

Leave a Reply to Brian Reid Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.