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

Error exception handling in PowerShell – Try catch finally 3 blocks rules

No comments

 29,571 total views,  3 views today

Error exception handling in PowerShell – Try catch finally – In this post, we will show 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.

Error Handling in Python (Try and E...
Error Handling in Python (Try and Except) (Video 43)

Error exception handling in PowerShell: Exception handling using try/catch/finally block PowerShell example

Refer to the below codes to handle error exceptions in PowerShell scripting:

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

Error exception handling in PowerShell scripting

Verify the log file with the above exception message: Error exception handling in PowerShell

Error exception handling in PowerShell demo output

Summary: Error exception handling in PowerShell (Try Catch Finally)

Thus in this post, we have learned 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 to create the folder.
  • Test-path PowerShell if in folder creation.
  • Use of log file PowerShell coding.

See Also: PowerShell tutorial for beginners

You may also like the below PowerShell tutorials

 

PDF Download Image

Download SharePoint Online & Office 365 Administration eBook

Buy the premium version of SharePoint Online & Office 365 administration eBook from here:



Buy SharePoint Online & Office 365 Administration eBook


 

Get the free demo PDF eBook from here:

FREE DOWNLOAD

Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.

 

About Post Author

Do you have a better solution or question on this topic? Please leave a comment