catch

catch is used to respond to terminating errors raised within try. catch can be used to respond to any exception, or a specific set of exception types. Each of the following is valid, if incomplete:

try { } catch { 'Catches any exception' } 
try { } catch [ExceptionType] { 'Catch an exception type' } 
try { } catch [ExceptionType1], [ExceptionType2] { 
    'Catch exception type 1 and 2' 
} 

In the following example, calling the ToString method on the null variable will throw an exception that triggers catch:

try { 
    $null.ToString() 
} catch { 
    Write-Host 'This exception has been handled' 
} 

When working with catch, the error record that was thrown is made available by using either the $_ variable or $PSItem:

try { 
    $null.ToString() 
} catch { 
    Write-Host $_.Exception.Message      # This is the same as... 
    Write-Host $PSItem.Exception.Message # ... this. 
} 
ForEach-Object and catch

If ForEach-Object is used, the current object in the pipeline is stored in the $_ variable. For the object from the input pipeline to be available inside catch, it must be assigned to another variable first.

catch statements can be limited to handle specific exception types:

$ErrorActionPreference = 'Stop' 
try { 
    # If the file does not exist, this will raise an exception of type ItemNotFoundException 
    $content = Get-Content C:doesnotexist.txt 
} catch [System.Management.Automation.ItemNotFoundException] { 
    Write-Host 'The item was not found' 
} 

If more than one type of error might be thrown by a block of code, multiple catch statements are supported. In the following example, an unauthorized access exception is thrown in response to an attempt to read a directory like a file:

$ErrorActionPreference = 'Stop' try { Get-ChildItem C:WindowsSystem32Configuration -Filter *.mof | ForEach-Object { $content = $_ | Get-Content } } catch [System.IO.FileNotFoundException] { Write-Host 'The item was not found' } catch [System.Management.Automation.ItemNotFoundException] { Write-Host 'Access denied' } 

In a similar manner, catch statements can be layered, starting with the most specific error type, working down to a broader condition. The first matching catch block will be used:

using namespace System.Management.Automation 
 
try { 
    throw [ItemNotFoundException]::new('Item not found')
} catch [ItemNotFoundException] { 
    Write-Host 'Item not found exception thrown' 
} catch {
    Write-Host 'Error thrown' 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.33.178