Bài giảng Kịch bản HDH: Module 9

ppt
Số trang Bài giảng Kịch bản HDH: Module 9 59 Cỡ tệp Bài giảng Kịch bản HDH: Module 9 2 MB Lượt tải Bài giảng Kịch bản HDH: Module 9 0 Lượt đọc Bài giảng Kịch bản HDH: Module 9 0
Đánh giá Bài giảng Kịch bản HDH: Module 9
4.1 ( 14 lượt)
Nhấn vào bên dưới để tải tài liệu
Để tải xuống xem đầy đủ hãy nhấn vào bên trên
Chủ đề liên quan

Nội dung

Module 9 Error Handling, Debugging, and Modularization Module Overview • Trap and handle run-time errors within a script • Debug scripts using a variety of techniques and tools • Modularize scripts by writing various types of functions Lesson 1: Variables, Arrays, Escaping, and More Operators • Explain the purpose of the $ErrorActionPreference variable and the use of the –ErrorAction and –ErrorVariable parameters • Write a trap construct to handle an error • Write a Try…Catch construct to handle an error Types of Errors in PowerShell • Syntax errors, which are usually the result of a mistype or misspelling.  Easiest to prevent and fix, usually identified through runtime error messages. • Logic errors, which means the script executes without error, but does not accomplish the results you intended.  Difficult to fix, and can require debugging.  Often caused by variable or property values that contain unexpected information. • Run-time errors, which are errors that you can anticipate in advance but cannot necessarily fix in advance.  Less difficult to fix, and can often be due to conditions in the environment at runtime, such as a computer that isn’t available on the network. Discussion: Run-time Errors • What kinds of errors could you foresee being able to anticipate within a script?  Connectivity to computers  Permissions to perform some task  Files, users, or other objects not being found  What else? Error Actions • Many cmdlets can continue to execute, even after certain types of non-terminating errors occur. • The $ErrorActionPreference shell variable instructs the shell what to do when a non-terminating error occurs. • Four possible values for $ErrorActionPreference…  Continue is the default, and instructs the cmdlet to display an error message and continue executing.  Stop tells the cmdlet to turn the non-terminating error into a terminating exception, meaning the cmdlet stops execution entirely.  SilentlyContinue instructs the cmdlet to continue executing without displaying an error message.  Inquire tells the cmdlet to interactively prompt the user for an action, enabling the user to select either Continue or Stop. Demonstration: Errors in Action • Learn how to use $ErrorActionPreference Poor Practice • Remember: Errors are a good thing.  Without errors, you will never discover where and when your script is inappropriately executing. • Some administrators have begun to add this command to the beginning of their scripts, to prevent errors from occurring: $ErrorActionPreference = "SilentlyContinue" • This is not a good practice.  Some administrators believe that this setting allows the script to continue when runtime errors occur, which it does.  However, a much better practice is to create logic that surrounds and anticipates expected runtime errors, rather than eliminating errors altogether. More Granular Error Actions • All PowerShell cmdlets support a set of common parameters.  These parameters are handled directly by the shell, and do not need to be specifically written by the cmdlet’s developer.  These parameters are not listed in each cmdlet’s help file.  The cmdlet’s help file may simply include “common parameters” at the end of its parameter list. • Common parameters can be discovered by using: help about_commonparameters • One common parameters is –ErrorAction, which accepts the same four values as $ErrorActionPreference.  Used for controlling error actions for a single cmdlet, rather than globally for the shell session. Demonstration: -ErrorAction • Learn how to use the –ErrorAction parameter. Trapping Exceptions • You can instruct the shell to notify you of terminating exceptions, enabling you to issue commands in response to those exceptions. • This is called error trapping.  You can only trap a terminating exception.  You cannot trap a non-terminating error, even if an error message is displayed. • Enabling trapping begins by setting the Stop value for –ErrorAction. • Once enabled with –ErrorAction Stop, two choices are available for actually trapping the error.  A Trap construct.  A Try…Catch construct. Exception Scope • Recall: A PowerShell session and its scripts work within multiple scopes.  The shell itself operates in the global scope.  Each script you write typically creates its own scope.  Running scripts and function creates a scope tree.  Rules exist for reading and writing between scopes. • Exceptions respect scope rules.  You should trap exceptions in the same scope they occur. Trap Constructs • Trap constructs are usually defined in scripts before the anticipated exception. A simple trap construct might resemble: trap { write-host "Exception trapped!" -fore yellow -back black continue } get-wmiobject win32_process -comp NotOnline -ea stop • At the end of a Trap construct, you will specify one of two available keywords:  Continue will resume execution on the command following the one that caused the exception, staying within the same scope as the trap  Break will exit the scope that contains the trap, passing the original exception to the parent scope for handling Trap Notes • The last slide’s trap was a general trap, meaning it will execute for any kind of exception. • Traps can also be defined for specific types of exceptions.  Creating a specific trap requires knowing its underlying .NET Framework class type. trap [System.Management.Automation.CommandNotFoundException] {"Command error trapped"} • The above example executes only for exceptions of the System.Management.Automation.CommandNotFoundException type.  This separation provides a way to define different error handling behavior for different types of problems.  However, determining the correct class type can be difficult. Demonstration: Using Trap • Learn how to use the trap construct. Try Constructs • A Try…Catch construct is more granular than a trap construct, and can be easier to use. try { gwmi win32_service -comp notonline -ea stop } catch { write-host "Error!" } finally { write-host "This executes either way" } • Three components exist for this construct…  The Try block defines the commands that you think might cause an error. These are the commands for which you’ve specified an – ErrorAction of Stop.  If an exception occurs, the code inside the Catch block is executed.  A Finally block will execute whether an exception occurred or not. Demonstration: Using Try • Learn how to use the try construct. What’s the Error? • Errors within a Trap or Try construct are addressed via a built-in $Error variable.  $Error[0] is the most-recent error.  $Error[1] is the next most-recent error.  …and so on… • The common parameter –ErrorVariable (aliased to –EV) can also be used to capture an error into a specified variable.  In the below code sample, -EV captures the error into the variable “myerr”.  Notice that “myerr” should not start with a “$”. try { gwmi win32_service -comp notonline -ea stop -ev myerr } catch { $myerr | out-file c:\errors.txt -append } Demonstration: Using -ErrorVariable • Learn how to use the –ErrorVariable parameter. Discussion: Combination Techniques • What other combinations of Try and Trap might you consider using? • In what situations? Lab A: Error Trapping and Handling • Exercise 1: Retrieving error information. • Exercise 2: Handling errors. • Exercise 3: Integrating error handling. Logon information Estimated time: 30 minutes. Lab Scenario • You are assigned to update a Windows PowerShell script that gathers audit information from machines on your network. • All errors must be logged to the Windows Event Log under the Windows PowerShell event log according to company policy. • This script is designed to run from the task scheduler, so the event log is the only way that you will be notified if the script is not completing its audit as necessary. Lab Review Review Questions • How can you find out what members the error records have? • What type of information are the error records providing you? • What type of tasks might you need to do regardless if a task succeeds or fails? • How would you find any cmdlets that work with the event log? Lesson 2: Debugging Techniques • Explain the goal and practices for debugging • Add debug trace messages to a script • Enable and disable debug trace messages in a script • Use the interactive step debugger to follow a script’s execution • Set, use, and remove breakpoints to debug a script • Use the Windows PowerShell ISE to debug a script Debugging Goal • Recall: The goal of debugging is to resolve logic errors.  The most common cause of logic errors is a variable or object property that contains a value other than what is expected or anticipated.  Debugging is designed to help you see what those variables and properties actually contain. • However, in order to begin debugging you must have an expectation of what your script will do, on a line-by-line basis.  Make notes of input values  Walk through scripts, line-by-line.  Make notes of what each line should do.  Document values that variables should contain. Discussion: Setting Expectations • As a group, review the script in your Student Guide. • Discuss what the script will do.  Make note of what object properties and variables should contain.  Write everything on a piece of paper of a whiteboard. Trace Messages • Trace messages help you follow the flow of script execution. They help you determine what values are actually within object properties and variables.  PowerShell does not provide automated trace messages.  You add these to your script by using the Write-Debug cmdlet. $var = Read-Host "Enter a computer name" • Write-Debug output is suppressed by default. Enable its output by Write-Debug "`$var contains $var" modifying the $DebugPreference variable at the beginning of your script. • Debug output is colored differently from normal output. Some IDEs can redirect debug output to a different pane. $DebugPreference = 'Continue' $DebugPreference = ‘SilentlyContinue' Demonstration: Using Write-Debug • Learn how to use the Write-Debug. Step Debugger • Reviewing hundreds of lines in a large script for trace messages can be time-consuming and difficult. • The shell’s step debugger enables script execution to occur one line at a time. Before executing each script line, you can choose to…  …pause (suspend) the script.  …review the contents of variables and object properties.  …execute the next line. • Two commands start and stop the step debugger: Set-PSDebug –step Set-PSDebug –off Demonstration: Using the Step Debugger • Learn how to use the step debugger. Breakpoints • Stepping through large scripts can also be time-consuming with the step debugger.  Clicking 200 times to move through a 200-line script takes a lot of time. • Breakpoints allow you to preset locations in a script where execution should suspend. Breakpoints are managed using a set of cmdlets:  Set-PSBreakpoint creates a new breakpoint condition  Remove-PSBreakpoint deletes a breakpoint condition  Disable-PSBreakpoint stops using a breakpoint condition, but leave it in place  Enable-PSBreakpoint enables a disabled breakpoint condition  Get-PSBreakpoint retrieves one or more breakpoint conditions Demonstration: Using Breakpoints • Learn how to use breakpoints. Debugging in the ISE • The ISE includes basic visual support for debugging, primarily in conjunction with breakpoints. Discussion: Which Technique is Best? • You will probably find yourself using a mix of debugging techniques, depending on the exact situation. • What are the situations where these techniques can work best?  Step debugger  Breakpoints  Write-Debug  Combinations? Lab B: Debugging a Script • Exercise 1: Debugging from the Windows PowerShell console. • Exercise 2: Debugging using the Windows PowerShell ISE. Logon information Estimated time: 30 minutes. Lab Scenario • Your manager has provided you with several Windows PowerShell scripts that are not functioning as expected. • The first script is EvaluatePingTimes, which loads a log of ping tests run against various machines on your WAN. It categorizes the results based on the expected network latency. However, there is a problem with the totals not matching the number of ping tests performed. • The second script is CalculatePerfMonStats, which imports some PerfMon data relating to memory usage on a server and calculates some statistics. For some of the counters, there seems to be a problem with how the numbers are read in, as some math errors are generated. Lab Review Review Questions • What are the key variables in your script and when are they used? • Are your commands getting the correct inputs? • Are there hard coded paths, file names, IP addresses, or other resources that may vary depending on where the script is run? • Are the variable names spelled correctly? • Are the variable names easy to distinguish from each other? Lesson 3: Modularization • Modularize one or more commands into a basic function • Write a parameterized function • Write a pipeline (filtering) function that outputs text • Write a pipeline (filtering) function that outputs custom objects • Explain the advantages and components of an advanced function Why Modularize? • Modularization is designed to make useful, reusable, self-contained components.  It makes scripting faster by enabling you to easily reuse portions of code from other projects. • PowerShell’s basic form of modularization is the function. Functions should generally…  Be as single-purpose and self-contained as possible.  Align to a real-world task.  Rely only on specific, defined input.  Never try to access information from outside itself.  Output data in a way that offers the maximum opportunity for reuse. Generally this means putting data in the pipeline. Discussion: What Should You Modularize? • What sorts of tasks can you envision performing in many different scripts?  Testing remote computer connectivity  Testing remote computer availability  Validating data  What else? Basic Functions • A basic function accepts no input, which means it is capable of performing its task without needing any additional information.  A basic function may product output, which can be piped elsewhere. • To create the function… Function Do-Something { # function code goes here } • To invoke the function… Do-Something Demonstration: Basic Functions • Learn how to write a basic function. Function Output • The Write-Output cmdlet…  Is the proper way to output information from a function.  Is aliased to “Write”. Write-Output $var Write $var $var • The Return keyword…  Is another mechanism for returning output, also to the pipeline. When complete, Return exits the function. • Note: Do not use Write-Host to output function data. It sends text to the Return $var console window and not the pipeline. Parameterized Functions • A parameterized function adds the ability to pass information into the function. • Two ways to define a function’s input parameters:  As part of the function declaration. Function Do-Something ($computername, $domainname) { # function code goes here }  Through an inside-the-function Param() declaration. Function Do-Something { Param( $computername, $domainname ) # function code goes here } Demonstration: Parameterized Functions • Learn how to write a parameterized function. Pipeline Input • Functions can also accept pipeline input.  In a parameterized function the shell automatically places pipeline input into a special variable named $input.  You do not need to declare $input as a parameter.  You will have to enumerate through $input, usually via ForEach-Object, as it will often contain multiple objects. function Do-Something { param ( $domain = 'contoso.com' ) foreach ($computer in $input) { write "Computer $computer, domain $domain" } } 'localhost','server1' | do-something -domain adatum Filtering Functions • A filtering function is specially designed to accept pipeline input. It consists of three named script blocks:  BEGIN executes once when the function is first called. You can use this block to perform any setup tasks that the function needs, such as connecting to a database.  PROCESS executes one time for each object that was piped in from the pipeline. Within this block, the special $_ placeholder contains the current pipeline object.  END executes once after all of the pipeline input objects have been processed. You can use this block to perform any cleanup tasks, such as closing a database connection. function Do-Something { BEGIN {} PROCESS {} END {} } Demonstration: Filtering Functions • Learn how to write a filtering function. • See how to use a standard input parameter in a filtering function. Function Output: Text • The filtering functions you’ve seen so far have run PowerShell commands, placing their output into the pipeline.  By doing so, these commands’ output becomes the function’s output.  Yet PowerShell doesn’t always do a good job of displaying output when the pipeline contains multiple different types of objects.  An alternate option is to construct your own output.  For example, you might output text to form column headers, then write each row of output.  PowerShell includes a formatting operator “-f” that makes it easier to create custom output. Demonstration: Text Function Output • Learn how to write a function that outputs formatted text. • Learn how to use the –f formatting parameter. Why Text Output is a Bad Choice • Text (string) output is inherently difficult to reuse.  It cannot be reformatted for table, CSV, XML, or other output using standard cmdlets.  Ensuring output data remains as an object ensures that it can be more easily worked with in the future. • The PSObject object..  Is a very simple, blank, custom object.  Serves as a blank canvas to which you attach your own properties, and ultimately your own data.  Enables you to keep otherwise-textual data in an object. $obj = New-Object PSObject $obj | Add-Member NoteProperty ComputerName $computername Write $obj Demonstration: Object Function Output • Learn how to write a function that outputs objects. More than One Way to Do Everything function Get-Inventory { PROCESS { $computer = $_ $os = gwmi win32_operatingsystem -comp $computer $bios = gwmi win32_bios -comp $computer $obj = new-object psobject $obj | select @{Label='ComputerName';Expression={$computer}}, @{Label='SPVersion';Expression={$os.servicepackmajorversion}}, @{Label='BIOSSerial';Expression={$bios.serialnumber}}, @{Label='BuildNo';Expression={$os.buildnumber}} } } gc names.txt | get-inventory gwmi win32_operatingsystem -computer (gc names.txt) | select @{Label='ComputerName';Expression={$_.__SERVER}}, @{Label='BuildNo';Expression={$_.BuildNumber}}, @{Label='SPVersion';Expression={$_.ServicePackMajorVersion}}, @{Label='BIOSSerial';Expression={ (gwmi win32_bios -comp $_.__SERVER).serialnumber }} Advanced Functions • An advanced function is a filtering function that specifies additional attributes for its input parameters.  These attributes make it possible for the function to look and behave almost identically to a cmdlet written in a .NET Framework language.  Advanced functions enables the creation of cmdlet-like structures that function similar to regular cmdlets. function Get-ComputerDetails { [CmdletBinding()] param ( [parameter(Mandatory=$true,ValueFromPipeline=$true)] [string[]]$computername ) BEGIN {} PROCESS {} END {} } Demonstration: Advanced Functions • See an example of an advanced function. Lab C: Modularization • Exercise 1: Generate an inventory audit report. • Exercise 2: Test network performance Logon information Estimated time: 45 minutes. Lab Scenario • You now have the knowledge and experience you need to begin crafting some very capable scripts to automate administrative activities. • You will use those skills to create two scripts, one for generating an inventory report and anther for testing network performance. Lab Review Review Questions • What parameter attributes are used to indicate that a parameter accepts pipeline input? • What is the advantage of using an advanced function instead of a regular function? Module Review and Takeaways Review Questions • What must you add to a cmdlet to ensure that any non- terminating errors it encounters will be trappable? • What command can be used to output “trace,” or debug messages? What must you include in a script to enable this output? • What kinds of breakpoints can you set? Are breakpoints valid only in a script, or can they be used directly from the command-line? • What are the advantages of a filtering function over a parameterized function? What are the advantages of an advanced function over other types of functions?
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.