Tuesday, February 12, 2013

Using Powershell and log files

So much of my initial learning of Powershell involved just banging out scripts and using trial and error to get going. Most of my understanding of what was happening was reading the console, which some nights were hours of going around in circles making a change, run it, make a change, run it.... In hindsight I should have first figured out how to log any data getting output, including errors.
This PowerShell script is my first attempt at getting some details about a set of sub sites in SharePoint and writing them to a text file and then opening the text file to screen so you can see the results.

If anything it has been a great learning experience.

add-pssnapin microsoft.sharepoint.powershell
CLS
## Set Variables
$site = "http://sp2010/dashboards"
$logFilePath = "c:\Temp\Powershell\Logs\sites.txt"
## Delete the file if it exists so the data does not append to the file
$deleteLogFile = Remove-Item -Path $logFilePath -Confirm:$false
## Create a function to handle the logic
function GetListOfSites
{
 ## Check to see if the log file exists
 $checkForLogFile = Test-Path $logFilePath
 if($checkForLogFile -ne $true)
 {
  $webs = Get-SPWeb $site
  ## Make sure the site we specified exists
  if($webs)
   {
    foreach($web in $webs.Webs)
    {
     ## Set the values to variables so we can format the output
     $webName = $web.Name
     $webDescription = $web.Description
     $webUrl = $web.Url
     $webID = $web.ID
     $webTemplate= $web.webtemplate
     $webTemplateID = $web.webtemplateID
     ## Getting fancy
     $siteDetails += 
      "---------SITE DETAILS------------",
      "Site: $webName",
      "Description:$webDescription",
      "Site Url:$webUrl",
      "Site ID:$webID",
      "Site Template:$webTemplate#$webTemplateID"
    }
    ## Output the values into a text file and save it to the file system
    $siteDetails  > $logFilePath 
    Write-Host "Log file has been generated, please wait a moment while the file opens..."
   }
  else
  {
   Write-Host "Site: $web not found, exiting."
  }
  ## Open the log file 
  Invoke-Item $logFilePath
 }
 else
 {
  Write-Host "Log file: $logFilePath not found, exiting."
 }
}
### MAIN
## Using Start-SPAssignment -Global to ensure that we don't leave a bunch of garbage in memory
Start-SPAssignment -Global
GetListOfSites
Stop-SPAssignment -Global

No comments: