Skip to main content

PowerShell to continue from catch block if there is an error

Below code snippet will help you to continue from catch block if there is error,

try{
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")| Out-Null
$Site = new-Object Microsoft.SharePoint.SPSite($siteCollUrl)

$alertResultsCollection = @()
$a = $ErrorActionPreference 
$ErrorActionPreference = "SilentlyContinue"

foreach($SiteColl in $Site.WebApplication.Sites)
{
if($SiteColl -ne $null)
{
Write-Host "Processing site " $SiteColl.URL

Try{                
foreach ($web in $SiteColl.AllWebs) 
{
if($web -ne $null)
{
Try{
foreach ($alert in $web.Alerts)
{                                            
$alertURL = $web.URL + "/"
$alertResult = New-Object PSObject
$alertResult | Add-Member -type NoteProperty -name "List_URL" -value $alertURL
$alertResult | Add-Member -type NoteProperty -name "Alert_Title" -value $alert.Title
$alertResult | Add-Member -type NoteProperty -name "Alert_Type" -value $alert.AlertType
$alertResult | Add-Member -type NoteProperty -name "Alert_Frequency" -value $alert.AlertFrequency
$alertResult | Add-Member -type NoteProperty -name "Delivery_Via" -value $alert.DeliveryChannels
$alertResult | Add-Member -type NoteProperty -name "Change_Type" -value $alert.eventtype
$alertResult | Add-Member -type NoteProperty -name "Subscribed_User_Name" -value $alert.User.Name
$alertResultsCollection += $alertResult                                    
}
}
catch {        
continue;
}
}
}
}
catch {        
continue;
}
}
$ErrorActionPreference = $a
}
##Export to CSV        
$alertResultsCollection | Export-CSV "D:\...\AllMossWebAppAlerts.CSV" -NoTypeInformation         
}
catch {        
$ErrorMessage = $_.Exception.Message
fn_AddResult "Error - $ErrorMessage"
fn_AddResult "\n"
}
finally {        
$webapp = $null   
$alertResultsCollection = $null
}

Reference: http://stackoverflow.com/questions/9884890/error-handling-and-minimize-script-output-to-end-user

Hope this helps!

Comments

Popular posts from this blog

Permission audit report for site and all sub sites using PowerShell

Use below script to get Permission audit report for site and all sub sites using PowerShell, Add-PSSnapin "Microsoft.SharePoint.PowerShell" $URL="https://intranet.contoso.com/sales/mysite/"      $site = Get-SPSite $URL      #Write the Header to "Tab Separated Text File"         "Site Name`t  URL `t Group Name `t User Account `t User Name `t E-Mail" | out-file "E:\Ulhas\UsersandGroupsRpt.txt"          #Iterate through all Webs       foreach ($web in $site.AllWebs)       {         #Write the Header to "Tab Separated Text File"         "$($web.title) `t $($web.URL) `t  `t  `t `t " | out-file "E:\Ulhas\UsersandGroupsRpt.txt" -append          #Get all Groups and Iterate through            foreach ($group in $Web.groups)         ...