Thursday, May 7, 2015

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!

Select and Delete text vertically in bigger text OR flat file

If you want to Select and Delete text vertically in bigger text OR any flat file use below command to do it. Example below: A BCEDF CDEF...