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 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
Verify the log file with the above exception message: Error exception handling in PowerShell
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
- PowerShell: How to pass multiple parameters into a function in PowerShell
- Using PowerShell create a log file
- Using PowerShell – Create a folder if not exists
- Encode and decode an URL using PowerShell coding
- Office 365: Getting started with SharePoint PnP PowerShell – installation
- In 2 steps convert a classic SharePoint page to modern using PnP
- Office 365: Retrieve hub sites and associated sites using PnP Powershell
- Create a modern team site using PnP PowerShell in SharePoint
- In 4 steps access SharePoint online data using postman tool
- SharePoint admin center: Learn SharePoint online administration in an hour – step by step
- SharePoint REST API: GET vs POST vs PUT vs DELETE vs PATCH
- Office 365: Understanding the hub site in SharePoint online
- Introduction to PowerShell