Hide Errors on a Single Command Line

# First method to hide errors on a single command line

Remove-AppxPackage -Package $Package.PackageFullName -ErrorAction SilentlyContinue

Hide Errors in a Block of Command Lines

#Second method to hide errors in a block of command lines

$ErrorActionPreference = “SilentlyContinue”

Remove-Item “c:\mount\ISO” -Force -Recurse

Remove-Item “c:\mount\Windows” -Force -Recurse

Remove-Item “c:\mount” -Force -Recurse

Remove-Item “C:\Scratch” -Force -Recurse

$ErrorActionPreference = “Continue”

Managing Error

It’s essential to have a mechanism in place to handle errors when they occur. Here’s an example of how you can manage errors in PowerShell:

try {
   # Code that can generate an error
     $connectionString = "Server=$dataSource;uid=$user; pwd=$PassSQL;Database=$database; Integrated Security=False;"
  $connection = New-Object System.Data.SqlClient.SqlConnection
  $connection.ConnectionString = $connectionString
  $connection.Open()
} catch {
   # if there's an error in the try, this code will be used
  Write-Host $_.Exception.Message -ForegroundColor Red
}


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.