Manual SharePoint Log Backups: Powershell Script

Because I think PowerShell is awesome. Here is my script I use to backup our SharePoint Logs. All the script does is to look fro any files in the the directory older than say 2 hours, copies them to a UNC path and uses 7Zip to compress them. In than way all 35GB of logs compress to around 180MB.. not that space is an issue though. I just think it is easier to manage like this.

This script is a modified version of my SQL backup and SSRS RDL backup powershell script.

"Set execution policy to [Unrestricted]"
Set-ExecutionPolicy Unrestricted
#note this is tested on PowerShell v2 and SSRS 2008 R2
#Compiled by Adrian Sullivan from various sources
#Date last modified: 12/01/2012
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Xml.XmlDocument");
[void][System.Reflection.Assembly]::LoadWithPartialName("System.IO");
#SECTION 3: ServerList > SharePoint
$servers = @("ZAV-SPS10") #
foreach($server in $servers)
 {
 $TargetFolder = "\\"+$server+"\c$\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS"
 $HoursAgo = 2
 $Days = -($HoursAgo/24) #imagine that 2/24 of one day.. 2 hours ne.
 $FileCounter = ((get-childitem -path $TargetFolder | where-object {$_.LastWriteTime -lt (get-date).AddDays($Days)}).count )
 if ($FileCounter -gt 0) {
 #create a timestamped folder, format similar to 2011-Mar-28-0850PM
 $folderName = Get-Date -format "yyyy-MM-dd-hhmmtt";
 $myBackupFolder = "\\server\c$\Backups\SharePointLogs\"+$server+"\"
 $fullFolderName = $myBackupFolder + $folderName;
 [System.IO.Directory]::CreateDirectory($fullFolderName) | out-null
 get-childitem -Path $TargetFolder |
 where-object {$_.LastWriteTime -lt (get-date).AddDays($Days)} |
 move-item -destination $fullFolderName
 # directories to use
 $base = $myBackupFolder
 $zipfile = $base + $server + ' LOGS.7z'
 $zipoption = ' Update Only "' + $zipfile + '"'
 # Files to compress
 $from = $base + "$folderName"
 # Create zip-file
 write-host "from:" $from
 write-host "zipopt:" $zipoption
 sz u "$zipfile" $from -mx5 #sz a "C:\Backups\" + $folderName +'.7z' +$myBackupFolder + 'RDL Backups.7z' -mx9
 remove-item "$fullFolderName" -Recurse
 }
 }

Enjoy.

Adrian

0 views0 comments

Recent Posts

See All