Friday, January 25, 2013

Error Handling and Logging in Powershell

When you run this script it will create a .csv file where you are running your script.

$URL = "siteurl"
$site = New-Object Microsoft.SharePoint.SPSite($URL)
$web = $site.openweb("")
#logging
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "Log2CSVFile"
$logfile = ("{0}{1}.csv" -f $filenamestart, $timestamp)

$header = "Head1,Head2"
$header | out-file -FilePath $logfile

try  {
           
            $list=$web.Lists["User Information List"]
            $listname = $list.title
            $msg = ("{0},{1}" -f "List:", "$listname")
            $msg | out-file -FilePath $logfile  -append
            Write-Host $list.title
      }
Catch
      {
          $msg = ( "{0},{1}" -f "Error occurred while reading list..:", $_)
            $msg | out-file -FilePath $logfile  -append
      }
     
      $i++


$web.Dispose()
$site.Dispose()




No comments:

Post a Comment

Followers