Tài liệu Windows 7 Resource Kit- P11 ppt

50 299 0
Tài liệu Windows 7 Resource Kit- P11 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Introduction to Windows PowerShell Scripting CHAPTER 13 453 Including Functions In Windows PowerShell 1.0 you could include functions from previously written scripts by dot-sourcing the script, but the use of a module offers greater flexibility because of the ability to create a module manifest that specifies exactly which functions and programming elements will be imported into the current session. diReCt FRoM tHe SoURCe Scopes and Dot-Sourcing James O’Neill, Evangelist Developer and Platform Group W indows PowerShell has three logical drives that can be thought of as holding the variables ENV: (which holds environment variables), VARIABLE: (which holds Windows PowerShell variables), and FUNCTION: (which holds Windows PowerShell functions). You can refer to the contents of an environment variable as $ENV:name. Windows PowerShell also has the concept of scopes, which can be sum- marized as “what happens in the script, stays in the script.” That is, a variable, alias, or function that is changed in a script won’t affect the Windows PowerShell environ- ment after the script terminates. This is usually a good thing. Actions taken at the command prompt affect a global scope, and scripts and functions only affect their local scope. A function that must change something in the global scope can explic- itly work on $Global:name. However, this still presents a problem for scripts that set variables we want to use later in the session or that load functions because, as soon the script is completed, the variables and functions are lost. Windows PowerShell allows a command to be prefixed with a dot (.) character. The dot operator says “Run this command in the current scope and not in a scope of its own,” a process that is known as “dot-sourcing.” Using Dot-Sourcing This technique of dot-sourcing still works in Windows PowerShell 2.0, and it offers the advantage of simplicity and familiarity. In the TextFunctions.ps1 script, two functions are created. The first function is called New-Line. The second function is called Get-TextStatus. The TextFunctions.ps1 script is seen here. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 13 Overview of Management Tools 454 TextFunctions.ps1 Function New-Line([string]$stringIn) { "-" * $stringIn.length } #end New-Line Function Get-TextStats([string[]]$textIn) { $textIn | Measure-Object -Line -word -char } #end Get-TextStats The New-Line function will create a line that is the length of an input text. This is helpful when you want an underline for text separation purposes that is sized to the text. Traditional VBScript users copy the function they need to use into a separate file and run the newly pro- duced script. An example of using the New-Line text function in this manner is seen here. CallNew-LineTextFunction.ps1 Function New-Line([string]$stringIn) { "-" * $stringIn.length } #end New-Line Function Get-TextStats([string[]]$textIn) { $textIn | Measure-Object -Line -word -char } #end Get-TextStats # *** Entry Point to script *** "This is a string" | ForEach-Object {$_ ; New-Line $_} When the script runs, it returns the following output. This is a string Of course, this is a bit inefficient, and it limits your ability to use the functions. If you have to copy the entire text of a function into each new script you want to produce or edit a script each time you want to use a function in a different manner, you dramatically increase your workload. If the functions were available all the time, you might be inclined to use them more often. To make the text functions available in your current Windows PowerShell console, you need to dot-source the script containing the functions into your console. You will need to use the entire path to the script unless the folder that contains the script is in your search path. The syntax to dot-source a script is so easy, it actually becomes a stumbling block for some people who are expecting some complex formula or cmdlet with obscure parameters. It is none of that—just a period (dot) and the path to the script that contains the function. This is Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Introduction to Windows PowerShell Scripting CHAPTER 13 455 why it is called dot-sourcing: you have a dot and the source (path) to the functions you want to include as seen here. PS C:\> . C:\fso\TextFunctions.ps1 When you include the functions into your current console, all the functions in the source script are added to the Function drive. This is seen in Figure 13-36. FIGURE 13-36 Functions from a dot-sourced script are available via the Function drive. Using Dot-Sourced Functions When the functions have been introduced to the current console, you can incorporate them into your normal commands. This flexibility should also influence the way you write the func- tion. If you write the functions so they will accept pipelined input and do not change the system environment (by adding global variables, for example), you will be much more likely to use the functions, and they will be less likely to conflict with either functions or cmdlets that are present in the current console. As an example of using the New-Line function, consider the fact that the Get-WmiObject cmdlet allows the use of an array of computer names for the –computername parameter. The problem is that the output is confusing, because you do not know which piece of information Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 13 Overview of Management Tools 456 is associated with which output. In this example, basic input/output system (BIOS) information is obtained from two separate workstations. PS C:\> Get-WmiObject -Class Win32_bios -ComputerName berlin, vista SMBIOSBIOSVersion : 080002 Manufacturer : A. Datum Corporation Name : BIOS Date: 02/22/06 20:54:49 Ver: 08.00.02 SerialNumber : 2096-1160-0447-0846-3027-2471-99 Version : A D C - 2000622 SMBIOSBIOSVersion : 080002 Manufacturer : A. Datum Corporation Name : BIOS Date: 02/22/06 20:54:49 Ver: 08.00.02 SerialNumber : 2716-2298-1514-1558-4398-7113-73 Version : A D C - 2000622 You can improve the display of the information returned by Get-WmiObject by pipelin- ing the output to the New-Line function so that you can underline each computer name as it comes across the pipeline. You do not need to write a script to produce this kind of display. You can type the command directly into the Windows PowerShell console. The first thing you need to do is to dot-source the TextFunctions.ps1 script. This makes the functions directly available in the current Windows PowerShell console session. You then use the same Get-WmiObject query that you used earlier to obtain BIOS information via WMI from two computers. Pipeline the resulting management objects to the ForEach-Object cmdlet. Inside the script block section, you use the $_ automatic variable to reference the current object on the pipeline and retrieve the System.Management.ManagementPath object. From the ManagementPath object, you can obtain the name of the server that is supplying the infor- mation. You send this information to the New-Line function so the server name is underlined, and you display the BIOS information that is contained in the $_ variable. The command to import the New-Line function into the current Windows PowerShell session and use it to underline the server names is shown here. PS C:\> . C:\fso\TextFunctions.ps1 PS C:\> Get-WmiObject -Class win32_Bios -ComputerName vista, berlin | >> ForEach-Object { $_.Path.Server ; New-Line $_.Path.Server ; $_ } The results of using the New-Line function are seen in Figure 13-37. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Introduction to Windows PowerShell Scripting CHAPTER 13 457 FIGURE 13-37 Functions that are written to accept pipelined input will find an immediate use in your daily work routine. The Get-TextStats function from the TextFunctions.ps1 script provides statistics based on an input text file or text string. When the TextFunctions.ps1 script is dot-sourced into the cur- rent console, the statistics that it returns when the function is called are word count, number of lines in the file, and number of characters. An example of using this function is seen here. Get-TextStats "This is a string" When the Get-TextStats function is used, the following output is produced. Lines Words Characters Property 1 4 16 In this section, the use of functions was discussed. The reuse of functions could be as simple as copying the text of the function from one script into another script. It is easier to dot-source the function. This can be done from within the Windows PowerShell console or from within a script. Adding Help for Functions There is one problem that is introduced when dot-sourcing functions into the current Windows PowerShell console. Because you are not required to open the file that contains the function to use it, you may be unaware of everything the file contains within it. In addition to functions, the file could contain variables, aliases, Windows PowerShell drives, or a wide variety of other things. Depending on what you are actually trying to accomplish, this may or may not be an issue. The need arises, however, to have access to help information about the features pro- vided by the Windows PowerShell script. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 13 Overview of Management Tools 458 Using the here-string Technique for Help In Windows PowerShell 1.0, you could solve this problem by adding a –help parameter to the function and storing the help text within a here-string. You can use this approach in Windows PowerShell 2.0 as well, but as discussed in the next section, there is a better approach to providing help for functions. The classic here-string approach for help is seen in the GetWmiClassesFunction.ps1 script. The first step that needs to be done is to define a switched parameter named $help. The second step involves creating and displaying the results of a here-string that includes help information. The GetWmiClassesFunction.ps1 script is shown here. GetWmiClassesFunction.ps1 Function Get-WmiClasses( $class=($paramMissing=$true), $ns="root\cimv2", [switch]$help ) { If($help) { $helpstring = @" NAME Get-WmiClasses SYNOPSIS Displays a list of WMI Classes based upon a search criteria SYNTAX Get-WmiClasses [[-class] [string]] [[-ns] [string]] [-help] EXAMPLE Get-WmiClasses -class disk -ns root\cimv2" This command finds wmi classes that contain the word disk. The classes returned are from the root\cimv2 namespace. "@ $helpString break #exits the function early } If($local:paramMissing) { throw "USAGE: getwmi2 -class <class type> -ns <wmi namespace>" } #$local:paramMissing "`nClasses in $ns namespace " Get-WmiObject -namespace $ns -list | where-object { $_.name -match $class -and ` $_.name -notlike 'cim*' } # end Get-WmiClasses function} #end get-wmiclasses Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Introduction to Windows PowerShell Scripting CHAPTER 13 459 The here-string technique works fairly well for providing function help. If you follow the cmdlet help pattern, it works well, as seen in Figure 13-38. FIGURE 13-38 Manually created help can mimic the look of core cmdlet help. The drawback to manually creating help for a function is that it is tedious. As a result, only the most important functions receive help information when using this methodology. This is unfortunate, because it then requires the user to memorize the details of the function contract. One way to work around this is to use the Get-Content cmdlet to retrieve the code that was used to create the function. This is much easier to do than searching for the script that was used to create the function and opening it in Notepad. To use the Get-Content cmdlet to display the contents of a function, you type Get-Content and supply the path to the function. All functions available to the current Windows PowerShell environment are available via the PowerShell Function drive. You can therefore use the following syntax to obtain the content of a function. PowerShell C:\> Get-Content Function:\Get-WmiClasses The technique of using Get-Content to read the text of the function is seen in Figure 13-39. FIGURE 13-39 The Get-Content cmdlet can retrieve the contents of a function. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 13 Overview of Management Tools 460 Using –help Function Tags to Produce Help Much of the intensive work of producing help information for your functions is removed when you use the stylized –help function tags that are available in Windows PowerShell 2.0. To use the help function tags, you place the tags inside the block comment tags when you are writing your script. When you write help for your function and employ the –help tags, the use of the tags allows for complete integration with the Get-Help cmdlet. This provides a seamless user experience for those utilizing your functions. In addition, it promotes the custom user- defined function to the same status within Windows PowerShell as native cmdlets. The experi- ence of using a custom user-defined function is no different than using a cmdlet, and indeed, to the user there is no need to distinguish between a custom function that was dot-sourced or loaded via a module or a native cmdlet. The –help function tags and their associated meanings are shown in Table 13-3. TABLE 13-3 Function –help Tags and Meanings HELP TAG NAME HELP TAG DESCRIPTION .Synopsis A very brief description of the function. It begins with a verb and informs the user as to what the function does. It does not include the function name or how the function works. The function synopsis appears in the SYNOPSIS field of all help views. .Description Two or three full sentences that briefly list everything that the function can do. It begins with “The <function name> function…” If the function can get multiple objects or take multiple inputs, use plural nouns in the description. The description appears in the DESCRIPTION field of all help views. .Parameter Brief and thorough. Describes what the function does when the para- meter is used and the legal values for the parameter. The parameter appears in the PARAMETERS field only in Detailed and Full help views. .Example Illustrates the use of a function with all its parameters. The first example is simplest with only the required parameters; the last example is most complex and should incorporate pipelining if appropriate. The example appears in the EXAMPLES field only in the Example, Detailed, and Full help views. .Inputs Lists the .NET Framework classes of objects that the function will accept as input. There is no limit to the number of input classes you may list. The inputs appear in the INPUTS field only in the Full help view. .Outputs Lists the .NET Framework classes of objects that the function will emit as output. There is no limit to the number of output classes you may list. The outputs appear in the OUTPUTS field only in the Full help view. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Introduction to Windows PowerShell Scripting CHAPTER 13 461 HELP TAG NAME HELP TAG DESCRIPTION .Notes Provides a place to list information that does not fit easily into the other sections. This can be special requirements required by the function, as well as author, title, version, and other information. The notes appear in the NOTES field only in the Full help view. .Link Provides links to other Help topics and Internet sites of interest. Because these links appear in a command window, they are not direct links. There is no limit to the number of links you may provide. The links ap- pear in the RELATED LINKS field in all help views. You do not need to supply values for all the –help tags. As a best practice, however, you should consider supplying the .Synopsis and the .Example tags, because these provide the most critical information required to assist a person in learning how to use the function. An example of using the –help tags is shown in the GetWmiClassesFunction1.ps1 script. The help information provided is exactly the same as the information provided by the GetWmiClassesFunction.ps1 script. The difference happens with the use of the –help tags. First, you will notice that there is no longer a need for the switched $help parameter. The reason for not needing the switched $help parameter is the incorporation of the code with the Get-Help cmdlet. When you do not need to use a switched $help parameter, you also do not need to test for the existence of the $help variable. By avoiding the testing for the $help variable, your script can be much simpler. You gain several other bonuses by using the special –help tags. These bonus features are listed here: n The name of the function is displayed automatically and displayed in all help views. n The syntax of the function is derived from the parameters automatically and displayed in all help views. n Detailed parameter information is generated automatically when the –full parameter of the Get-Help cmdlet is used. n Common parameters information is displayed automatically when Get-Help is used with the –detailed and –full parameters. In the GetWmiClassesFunction.ps1 script, the Get-WmiClasses function begins the help section with the Windows PowerShell 2.0 multiline comment block. The multiline comment block special characters begin with the left angle bracket followed with a pound sign (<#) and end with the pound sign followed by the right angle bracket (#>). Everything between the multiline comment characters is considered to be commented out. Two special –help tags are included: the .Synopsis and the .Example tags. The other –help tags that are listed in Table 13-3 are not used for this function. <# .SYNOPSIS Displays a list of WMI Classes based upon a search criteria .EXAMPLE Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 13 Overview of Management Tools 462 Get-WmiClasses -class disk -ns root\cimv2" This command finds wmi classes that contain the word disk. The classes returned are from the root\cimv2 namespace. #> When the GetWmiClassesFunction.ps1 script is dot-sourced into the Windows PowerShell console, you can use the Get-Help cmdlet to obtain help information from the Get-WmiClasses function. When the Get-Help cmdlet is run with the –full parameter, the help display seen in Figure 13-40 appears. FIGURE 13-40 Full help obtained from the function Get-WmiClasses The complete GetWmiClassesFunction.ps1 script is seen here. GetWmiClassesFunction1.ps1 Function Get-WmiClasses( $class=($paramMissing=$true), $ns="root\cimv2" ) { <# .SYNOPSIS Displays a list of WMI Classes based upon a search criteria .EXAMPLE Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... $env:path C: \Windows\ system32;C: \Windows; C: \Windows\ System32\Wbem;C: \Windows\ System32 \Windows System Resource Manager\bin;C: \Windows\ idmu\common;C: \Windows\ system32 \WindowsPowerShell\v1.0\ PS C:\> $env:path += ";C:\fso" PS C:\> $env:path C: \Windows\ system32;C: \Windows; C: \Windows\ System32\Wbem;C: \Windows\ System32 \Windows System Resource Manager\bin;C: \Windows\ idmu\common;C: \Windows\ system32 \WindowsPowerShell\v1.0\;C:\fso... this resource kit Categories of policy settings that are prefixed with an asterisk (*) are new in Windows 7 and Windows Server 2008 R2, and categories of policy settings prefixed with a double asterisk (**) are enhanced with new policy setting subcategories of policy settings in Windows 7 and Windows Server 2008 R2 TABLE 14-1  New and Enhanced Group Policy Areas in Windows 7, Windows Server 2008 R2, Windows. .. Group Policy Features in Windows 7 and Windows Server 2008 R2 Windows 7 and Windows Server 2008 R2 build on the foundation of Group Policy improvements made in Windows Vista and Windows Server 2008 The key improvements to Group Policy in Windows 7 and Windows Server 2008 R2 are as follows: n n Default Starter GPOs  Windows 7 and Windows Server 2008 R2 now include a number of default Starter GPOs that... from Windows Vista SP1 with RSAT or Windows Server 2008 Preference client-side extensions (CSEs) are included in Windows Server 2008, whereas downloadable versions of the preference’s CSEs are available for Windows Vista RTM or later, Windows XP SP2 or later, and Windows Server 2003 SP1 or later from the Microsoft Download Center New Group Policy Features in Windows 7 and Windows Server 2008 R2 Windows. .. improvement, see the section titled “Group Policy Policy Settings in Windows 7 later in this chapter Windows PowerShell cmdlets for Group Policy  In Windows 7 and Windows Server 2008 R2, you can now use Windows PowerShell to create, edit, and maintain GPOs using the new Windows PowerShell cmdlets for Group Policy available within the Windows Server 2008 R2 GPMC This allows administrators to automate... Starting in Windows 7 and Windows Server 2008, however, these advanced audit policy categories can be managed using Group Policy and are found under Computer Configuration\Policies \Windows Settings \Security Settings\Advanced Audit Policy Configuration For more information about this feature, see Chapter 2, “Security in Windows 7. ” n Application Control Policies  Group Policy in Windows 7 and Windows Server... of users on these clients This chapter describes the new features of Group Policy in the Windows 7 and Windows Server 2008 R2 operating systems and how they build on the earlier Group Policy enhancements introduced in Windows Vista and Windows Server 2008 Understanding Group Policy in Windows 7 Windows Vista and Windows Server 2008 introduced new and enhanced features in the area of Group Policy management,... client computers This new policy setting can be found under Computer Configuration\Policies \Windows Settings\Name Resolution Policy Group Policy Policy Settings in Windows 7 Windows Vista and Windows Server 2008 introduced many new categories of policy settings and enhanced some existing policy settings Windows 7 and Windows Server 2008 R2 also present new policy setting categories by which administrators... Directory Domain Services (AD DS) is deployed Windows 7 and Windows Server 2008 R2 build on the foundation of Group Policy improvements made in Windows Vista and Windows Server 2008 by adding powerful new features that make enterprise network management easier than ever For the benefit of administrators who are migrating desktop computers from Windows XP to Windows 7, this section begins by reviewing the... executable files, scripts, Windows Installer files (.msi and msp files), and dynamic-link libraries (DLLs) For more information on AppLocker, see Chapter 24, “Managing Client Protection.” Understanding Group Policy in Windows 7 Chapter 14 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 4 87 n Name Resolution Policy  Group Policy in Windows 7 and Windows Server 2008 R2 has . $env:path C: Windows system32;C: Windows; C: Windows System32Wbem;C: Windows System32 Windows System Resource Managerin;C: Windows idmucommon;C: Windows system32. C: Windows system32;C: Windows; C: Windows System32Wbem;C: Windows System32 Windows System Resource Managerin;C: Windows idmucommon;C: Windows system32 WindowsPowerShellv1.0;C:fso A

Ngày đăng: 21/01/2014, 11:20

Từ khóa liên quan

Mục lục

  • Cover

    • Copyright Page

    • Contents at a Glance

    • Table of Contents

    • Acknowledgments

    • Introduction

    • Part I: Overview

      • Chapter 1: Overview of Windows 7 Improvements

        • Windows 7 Improvements by Chapter

          • User Interactions

          • Performance

          • Mobility

          • Reliability and Supportability

          • Troubleshooting

          • Deployment

          • Windows 7 Editions

            • Windows 7 Starter

            • Windows 7 Home Basic

            • Windows 7 Home Premium

            • Windows 7 Professional

            • Windows 7 Enterprise

            • Windows 7 Ultimate

            • Choosing Software and Hardware

              • Windows 7 Software Logo

              • Hardware Requirements

              • Summary

Tài liệu cùng người dùng

Tài liệu liên quan