Exception or Error handling in PowerShell -Try/Catch/Finally Block Example

No comments

In this post I will show that how we can handle the exception in PowerShell coding using the try/catch/finally block and how we can write the error or exception message into the log file.

Exception handling using try/catch/finally block PowerShell example:

cls
$fileName = "File_Uploading_Report"
$enddate = (Get-Date).tostring("yyyyMMddhhmmss") 
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"   
$invocation = (Get-Variable MyInvocation).Value  
$directoryPath = Split-Path $invocation.MyCommand.Path

$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))  
        {  
            New-Item -ItemType directory -Path $directoryPathForLog
               
        }


$logPath = $directoryPathForLog + "\" + $logFileName
$isLogFileCreated = $False 

function Write-Log([string]$logMsg)  
{   
    if(!$isLogFileCreated){   
        Write-Host "Creating Log File..."   
        if(!(Test-Path -path $directoryPath))  
        {  
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   
        else   
        {   
            $script:isLogFileCreated = $True   
            Write-Host "Log File ($logFileName) Created..."   
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
            Add-Content -Path $logPath -Value $logMessage   
        }   
    }   
    else   
    {   
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
        Add-Content -Path $logPath -Value $logMessage   
    }   
}

#####How to use?################################

$sampleLogMessage="This is a sample log entry";
Write-Log $sampleLogMessage
Write-host "Log file entry has been successfully tested"

#####How to use ends here#######################


#############Exception Handling in PowerShell################################
Try 
{
       
    $Password="MyPassword"
    $TargetLibrary="MyLibrary"
    $securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force  
    #Setup the Context
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SPOSiteURL)
    $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $securePassword)
    
    $list = $ctx.Web.Lists.GetByTitle($TargetLibrary)
    $ctx.Load($list)
    $ctx.ExecuteQuery()
} 
 Catch 
{
            
        $ErrorMessage = $_.Exception.Message +"in uploading File!: " +$tarGetFilePath
        Write-Host $ErrorMessage -BackgroundColor Red
        Write-Log $ErrorMessage 


}
Finally
{
 Write-Host "I will be executed after the error."
}
#############Exception Handling in PowerShell ends here######################

 

Exception handling using try/catch block PowerShell example: Debugging

ExceptionHandlingUsingTryCatchBlockInPowerShell

Verify the log file with the above exception message:

ExceptionHandlingUsingTryCatchBlockInPowerShell2

Summary:

Thus in this post we have learned that how to use “try/catch/finally” blocks in PowerShell coding for error or exception handling. And also learned how to use the below PowerShell command in the code:

  • New-item in create folder.
  • Test-path PowerShell if in folder creation.
  • Use of log file PowerShell coding.