Sample PowerShell script to copy the SharePoint ULS logs of a server to a file share
I didn't find a simple script to do that on the web, so I'm sharing the following very sample script.
This script collects and copies the SharePoint logs file (ULS files) in another location (for example a share).
This script is very very simple, but could be useful in some cases. This script is done for SharePoint 2010.
Add-PsSnapin Microsoft.SharePoint.PowerShell
#region Init parameters
#### You can edit the following parameters to change the configuration
###############################################################################################
$ulsLogsPath = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS\"
$destinationPath = "\\IBPCONTENTDPL\Share\"
$removeAfterCopy = $false
#### End of parameters
###############################################################################################
#endregion Init parameters
#region Functions
## <summary>
## This methods helps to check if a file is an ULS file or not.
## </summary>
function Check-IsULSLogFile($file)
{
#Checks if it's not a directory
if ($item.Attributes -eq "Directory")
{
return $false
}
#Checks if the name starts with current server name
$computerName = gc env:computername
if ($item.Name.StartsWith($computerName) -eq $false)
{
return $false
}
#Checks if it's not created after the retention duration (1 day)
if ($item.CreationTime -gt ($(Get-Date).AddDays(-1)))
{
return $false
}
return $true
}
#endregion Functions
"***** Start ULS collector script *****"
if ((Test-Path $ulsLogsPath) -eq $false)
{
"The input directory doesn't exist at '$ulsLogsPath'"
}
else
{
if ((Test-Path $destinationPath) -eq $false)
{
"The destination directory doesn't exist at '$destinationPath'"
}
else
{
#Get all the items inside the source path
$items = get-childitem "$ulsLogsPath" -recurse | Where {$_.extension -eq ".log"}
$count = $items.Count
"Found $count files to analyze"
#Get the full target path for this computer
$computerName = gc env:computername
$path = $destinationPath;
if ($path.EndsWith("\") -eq $false)
{
$path += "\"
}
$path += $computerName + "\"
#Checks if the full target path exists, if not creates the folder for this server
if ((Test-Path $path) -eq $false)
{
"Destination folder '$path' doesn't exist, create it."
New-Item $path -type directory
}
foreach ($item in $items)
{
if (Check-IsULSLogFile($item))
{
if ($removeAfterCopy -eq $false)
{
Copy-Item $item.FullName $path
$name = $item.Name
"File $name has been successfully copied in path '$path'"
}
else
{
Move-Item $item.FullName $path -force
$name = $item.Name
"File $name has been successfully moved in path '$path'"
}
}
}
}
}
"***** End of collector script *****"
Comments
- Anonymous
July 17, 2014
Very nice--exactly what I was looking for--thanks!