Script to Purge IIS Logs on Servers

Scenario:  Some applications, such as IIS, will create daily logs on your server. These IIS logs can be big in size and will not automatically purge off.  The script below will purge all but 7 days worth of IIS logs for each server listed in the $servers variable.

PowerShell Script (PurgeIISLogs.ps1)

$servers = “MBX01″,”MBX02”

$servers | %{ 

dir $_c$inetpublogslogfiles -recurse |  Where { ((get-date)-$_.LastWriteTime).days -gt 5 } | Remove-Item -Force

}

To schedule this script to run as a daily task, setup a second script (a batch script) that calls the Powershell script and executes it. The batch script is below.

Batch Script (PurgeIISLogs.bat)

%SystemRoot%system32WindowsPowerShellv1.0powershell.exe -NoProfile -ExecutionPolicy Bypass -Command “& ‘c:TASKPurgeIISLogs.ps1′”

Manually Purge Log Files from Exchange Database Copies

Purpose:  The purpose of this document is to provide instruction on how to safely purge Exchange Database log files manually after log file buildup on a Exchange Server.  Log files are stored in the logs directly until an Exchange aware Full or Incremental Backup is successfully ran.  Once Exchange is aware that this backup is complete, Exchange will purge the log files.  If a backup has not ran successfully, then log files will continue to be created in the logs directory and the previous log files will still exist, consuming space.  Over time, this will fill up the hard drive where the log files are kept.  This manual purge is done live, meaning the instructions below happen while the Exchange Database remains mounted.  In the instructions below, we are using an Exchange Database DB53 that has 4 Database Copies; 1 Mounted, 3 Healthy.

Overview of the Instructions Below:

1. Capture and isolate the Log Files that will moved and purged into a text file.

2. Using Excel, open that text file and format it. Format meaning remove unwanted rows such as Header/Footer rows and removing log files for dates you wish to not remove.  For Example, I want to remove all the log files EXCEPT the last day or two. **NOTE do not remove the newest log files – give yourself a buffer**.

3. Using Excel, we will formulate the Move-Item and Remove-Item scripts to be ran on each server that holds the database copy.  From one database copy, we will move the log files to another serverstorage location.  From the other 3 database copies, we will purge the log files.  Purging log files is quick, moving log files is a little bit slower.

4. Run the appropriate .ps1 script that will be created on each server that holds a database copy.

Instructions:

Capture and Isolate the Log Files:
1. Determine the LogFilePrefix for the database:
get-mailboxdatabase DB53 | FL LogFilePrefix

2. Determine the Database Copies Status to figure out which copy is mounted, healthy, or other status. Of the Mounted/Healthy Database Copies, choose 1 Database Copy to move the logs that wish to be purged to a storage share and purge the logs on the remaining copies. This ensures a copy of the logs exist in the event of a problem.

Get-mailboxdatabasecopystatus DB53

3. In a command prompt, run the following DIR command. It will put the results into the text file specified.  You will be using the LogFilePrefix you have found in Step1.

dir MBX01e$db53logsE01*.log > C:usersstevedesktopDB53.txt

In Excel, Open the Text File and Format It

4. Open Excel and then Open that Txt File.  Make sure during the Text Import Wizard (when opening the txt file in Excel), the logs are in their own column. I chose fixed width in the Wizard. Click on Finish.

5. Remove the rows that do not contain a log file (Very Beginning Rows and Very Last Rows).

6. Sort the dates (if not sorted already) and remove the rows of the date range that you do not wish to delete. For Example, I want to purge all log files EXCEPT for the last 2 days’ worth.

In Excel, Create the PowerShell Code used to Move/Purge Log Files

7. In Column F (Or the next Open Column) type this formula in and Copy on down to the last row. Note: Cell E2 is the log file name. You may have to change this value if the log file name exists in a different cell.

=”Write-Host “&E2&”; Move-Item E:DB53Logs”&E2&” FileSvr1filesDB53″ 

8. In Column G (or the next Open Column) type this formula in and Copy on down to the last row. Note: Cell E2 is the log file name. You may have to change this value if the log file name exists in a different cell.

=”Write-Host “&E2&”; Remove-Item E:DB53Logs”&E2&” -force”

 9. Copy the Contents out of the Move-Item Column and paste into notepad. Save that notepad file as DB53_move.ps1.  Copy this and run this on the server that has the database copy for you wish to move the log files.

10. Copy the Contents out of the Remove-Item Column and paste into notepad. Save that notepad file as DB53_remove.ps1.  Run this in PowerShell on the servers that have the remaining database copies.

Now you have carefully Moved/Purged the Log Files of that database. You now have bought yourself enough free space on the hard drives to work out your backup issues.

Export Mail into a PST between two dates

Scenario:  You want to export mail from a mailbox into a PST with a filter of between two dates.

Run this command:

New-MailboxExportRequest -ContentFilter {(Received -gt ’01/01/2014′) -and (Received -lt ’04/01/2014′)} -Mailbox “testuser1” -Name testuser1 -FilePath ServerSharetestuser1.pst -baditemlimit 999 -acceptlargedataloss

Changes to the public group memberships cannot be saved; You do not have permission to perform the operation on the object

Issue: Customer is the owner of a distribution group called Testgroup
When trying to add employees from Outlook he gets the following error message:
Changes to the public group memberships cannot be saved; You do not have permission to perform the operation on the object

Cause: This happens, because the distribution group the user wants to modify was created on Exchange server 2007. Type this command from PowerShell to confirm that distribution group has legacy version attribute:
get-distributionGroup testgroup | Fl *Version

This is legacy version:  ExchangeVersion : 0.1 (8.0.535.0)

Solution: The distribution group needs to be updated to later exchange version. Use  Exchange server 2010 or 2013 PowerShell  to update the Exchange version attribute of the distribution group
From Exchange 2013 or Exchange 2010 powershell, type Set-distributiongroup TestGroup. That command updates the exchange version for the DG.

To Verify, type:  get-distributionGroup testgroup | Fl *Version

Version should now display ExchangeVersion: 0.10 (14.0.100.0)

Forward emails that comes to a mailbox to an external address and also keep the mail.

Scenario: you want to forward emails that comes to a particular mailbox to an external address and also keep the mail.

Resolution: Create a mail contact using powershell or Exchange 2013 ECP. If you have exchange 2010 users, you can also use the mgmt console

From Powershell, type Set-Mailbox -Identity ‘testmailbox’ -DeliverToMailboxAndForward:$true -ForwardingAddress ‘mailcontactalias’

The error “Members can’t remove themselves from security groups. Please set the group to Closed for requests to leave.” when editing a distribution group.

Scenario: When editing the managers of a distribution group, this error is displayed:

Members can’t remove themselves from security groups. Please set the group to Closed for requests to leave.

Resolution: Set the MemberDepartRestriction to closed for that distribution group.

set-distributiongroup  <alias of group> -memberdepartrestriction closed

After a Database Reseed, the following error is displayed: Error: Unable to delete logs at ‘C:DB01Logs’. The database has been seeded successfully. If any obsolete log files exist, manualy delete them to prevent database divergence.

Scenario:  During a Exchange database reseed, you get the following error when the reseed is finished:

Update-MailboxDatabaseCopy DB01MBX02 -DeleteExistingFiles

A source-side operation failed. Error An error occurred while performing the seed operation. Error: Unable to delete logs at ‘C:DB01Logs’. The database has been seeded successfully. If any obsolete log files exist, manualy delete them to prevent database divergence. Error: System.IO.IOException: The file or directory is corrupted and unreadable.

Resolution:  Format the hard drive and perform the reseed again.

Clearing out a corrupt transport queue.

MSExchange Transport Service will not start. Application eventlog has logged Source ESE, EventID 529 with this in the details. bytes failed verification due to a corrupted checksum log record. The read operation will fail with error. If this condition persists, restore the logfile from a previous backup.

Stop the MSExchange Transport Service

Go to C:Program FilesMicrosoftExchange ServerV14TransportRolesdataQueue (if installed in default location)

Create New folder OLDQueue,

Move all files in the Queue folder to new OLDQueue folder.

Start the MSExchange Transport Service

A new database will be created and your queue will be cleared.

Exchange Queue Error: 451 4.4.0 dns query failed. the error was dns query failed with error ErrorRetry

Scenario:  You receive complaints that users are experiencing the following symptoms with their Exchange 2013 mailbox:

  • Outlook:  Messages are getting stuck in the OutBox when sending
  • OWA: Messages are getting stuck in the Drafts Folder when sending

During investigation, you run this command: get-queue -server ExMbx1 | FL Identity, Status, MessageCount, LastError and find all of the queues on that transport server have a high MessageCount and this LastError:  451 4.4.0 dns query failed. the error was dns query failed with error ErrorRetry

You have verified your DNS settings on the network adapter are correct and you were successful at using NSLOOKUP to resolve the MX record of one of the domains that you are having trouble with (instructions below on how to do this).

NSLOOKUP instructions:
1. From command line, type nslookup
2. set q=mx    (or  set type=mx)
3. domain.com

Cause:  Exchange transport service allows you to set and use external and internal dns servers different from network card dns settings. Internal DNS server setting was pointing to dns servers that were decommissioned

Solution:  Remove the custom DNS entries in Exchange. This makes Exchange use the network adapters DNS. Follow the steps below to resolve via EAC or PowerShell

Via EAC:
1. Once in EAC/ECP, navigate to Servers and open the server properties.
2. Click on DNS Lookups.
3. Make sure the Internal and External DNS lookups are set correctly.  The internal and External DNS settings need to match DNS setting on the network card IP configuration. Type the current DNS settings or leave it blank. Blank forces Exchange transport service to use network card DNS setting

Via Shell:
1. Use get-transportserver ExMbx1 | FL *DNS* to verify your settings.
2. You want to use the set-transportserver command to set it back to all network adapters or change the custom IP Range.

For Example:  You may wish to change the Internal DNS to use all network adapters and not custom by running:
set-transportserver ExMbx1 -InternalDNSProtocolOption Any

OR type the following to set it to Null

set-transportserver ExMbx1 -InternalDNSServers $null

Add a new email address to mailboxes in bulk

This one liner reads a list of user names from a text file, fetches the current set of proxy email addresses, and adds a new “test.com” SMTP email address to each mailbox.

Get-Content Users.txt | Get-Mailbox |% {$_.EmailAddresses.add(“smtp:$($_.SamAccountname)@test.com”); Set-Mailbox -Identity:$_.Identity -EmailAddresses:$_.EmailAddresses}