- <#
- .SYNOPSIS
- Shows Try/Catch/Finally using Powershell
- .DESCRIPTION
- This is an MSDN Sample, re-written in PowerShell
- .NOTES
- File Name : get-trycatchfinally.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell V2 CTP3
- .LINK
- Original script posted to:
- http://pshscripts.blogspot.com/2009/01/get-trycatchfinallyps1.html
- MSDN Sample at:
- http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
- .EXAMPLE
- PS C:\foo> .\Get-TryCatchFinally.ps1
- Error in conversion
- Error record: Cannot convert value "Some string" to type "System.Int32". Error: "Input string was not in a correct format."
- $i = 123
- $i = System.Int32
- #>
- ###
- # Start of script
- ###
- # Create some explicitly typed values
- [int] $i = 123
- [string] $s = "Some string"
- [object] $o = $s
- # Now try to convert an object into an integer (which will fail)
- try {
- # Invalid conversion; $o contains a string not an int
- $i = [int] $o
- }
- # catch the error and display
- catch {
- "Error in conversion"
- "Error record: {0}" -f $Error[0]
- }
- # Clean up
- finally {
- "`$i = {0}" -f $i
- "`$i = {0}" -f $i.gettype()
- }
- # End of Script
This blog contains PowerShell scripts, more PowerShell scripts and still more PowerShell scripts. Occasionally you may see some organisational posts.
Showing posts with label finally. Show all posts
Showing posts with label finally. Show all posts
Wednesday, 21 January 2009
Get-TryCatchFinally.ps1
Labels:
catch,
finally,
powershell,
PowerShell scripts,
try
Sunday, 23 November 2008
Catch-Error.ps1
<# .SYNOPSIS Demonstrates try/catch/finally in V2 .DESCRIPTION Shows a simple example of the try/catch/finally syntax introduced into PowerShell V2 CTP3 . The script divides by zero which creates an exception. The PowerShell parser is smart enough to recognise any attempt to divide by "0" and therefore does not generate the run time error. .NOTES File Name : Show-TryCatchFinally.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 .LINK http://pshscripts.blogspot.com/2008/11/catch-errorps1.html #> ## # Start of script ## # Try something that fails $one=1 $zero=0 Try { $one/$zero } Catch{ 'Caught in a catch block' $Error[0] } Finally {'All done with trying and catching' }
Labels:
catch,
error handling,
finally,
PowerShell V2,
scripts,
try
Subscribe to:
Posts (Atom)