Display Error Codes with PowerShellDisplay Error Codes with Microsoft PowerShellMy mission on this page is to show you how to display error codes, furthermore, I will explain how to translate meaningless numbers into meaningful phrases. Topics for Error Codes in PowerShell
♣ Mission to Display Error Messages When Creating SharesWe need a vehicle to examine error codes. That vehicle will be creating a file share. For example, if the share already exists, when you run the script again, it returns error code 22. Not only can we trap this return value, but also we can 'Switch' 22 to a more meaningful message, such as 'Duplicate Share' Example 1: How to Create a PowerShell FunctionNaturally, any function needs a name, in this case I chose 'errMsg'. As this is a simple function, it only has one argument, $intErr. The rest of the function is taken up with a 'Switch' statement, or a series of statements corresponding to each error value. # Microsoft PowerShell Function only Function errMsg($intErr) Note 1: This code does not do anything by itself, it is merely a stage in producing the script. Example 2: Using a PowerShell Function to Display an Error CodePreparation and Pre-requisites To understand Example 2, I suggest that you familiarise yourself with the logic of my 'Create a Share' example. Then you can match my thinking to the second portion of the script below. When you understand my script, copy and paste the code into PowerShell, or better, create a cmdlet with .ps1 extension. Then call that file from within PowerShell with ./filename. # Using a PowerShell Function Function errMsg($intErr) $FolderPath = "C:\Temp" Note 1: Working backwards! On the last line, errMsg($Success.returnValue) runs a number through the function, which I created in the first part of the script. The result is a meaningful message controlled by that function's Switch statement. Note 2: Next, let us study the $Success variable. $Success=$objWMI.... results in an attempt to create the share, however, it exits, therefore the .returnValue is 22.
Guy Recommends: SolarWinds Engineer's Toolset v10
|
||||||
Download my ebook:
|
*
|
|
|
|
Home Copyright © 1999-2009 Computer Performance LTD All rights reserved Please report a broken link, or an error. | |