• No results found

Using Modules

In document Windows PowerShell 2.0 (Page 93-98)

Windows PowerShell modules are self-contained, reusable units of execution that can include:

N Script functions that are made available through .PSM1 fi les.

N .NET assemblies that are compiled into .DLL fi les and made available through

.PSD1 fi les.

N PowerShell snap-ins that are made available in .DLL fi les. N Custom views and data types that are described in .PS1XML fi les.

Most modules have related snap-ins, .NET assemblies, custom views, and custom data types. In the .PSD1 fi les that defi ne the included assemblies, you’ll fi nd an as- sociative array that defi nes the properties of the module, as is shown in the example that follows and summarized in Table 3-6.

@{

GUID="{8FA5064B-8479-4c5c-86EA-0D311FE48875}" Author="Microsoft Corporation"

CompanyName="Microsoft Corporation"

Copyright="© Microsoft Corporation. All rights reserved." ModuleVersion="1.0.0.0"

Description="Powershell File Transfer Module" PowerShellVersion="2.0"

CLRVersion="2.0"

NestedModules="Microsoft.BackgroundIntelligentTransfer.Management" FormatsToProcess="FileTransfer.Format.ps1xml"

RequiredAssemblies=Join-Path $psScriptRoot "Microsoft. BackgroundIntelligentTransfer.Management.Interop.dll" } @{ GUID="{8FA5064B-8479-4c5c-86EA-0D311FE48875}" Author="Microsoft Corporation" CompanyName="Microsoft Corporation"

Copyright="© Microsoft Corporation. All rights reserved." ModuleVersion="1.0.0.0"

Description="Powershell File Transfer Module" PowerShellVersion="2.0"

CLRVersion="2.0"

NestedModules="Microsoft.BackgroundIntelligentTransfer.Management" FormatsToProcess="FileTransfer.Format.ps1xml"

RequiredAssemblies=Join-Path $psScriptRoot "Microsoft. BackgroundIntelligentTransfer.Management.Interop.dll" }

TABLE 3-6 Common Properties of Modules

PROPERTY DESCRIPTION

Author, CompanyName, Copyright Provides information about the creator of the module and copyright.

CLRVersion The common language runtime (CLR)

version of the .NET Framework required by the module.

Description The descriptive name of the module.

FormatsToProcess A list of FORMAT.PS1XML files loaded by

the module to create custom views for the module’s cmdlets.

GUID The globally unique identifier (GUID) of

the module.

ModuleVersion The version and revision number of the

module.

NestedModules A list of snap-ins, .NET assemblies, or both

loaded by the module.

PowerShellVersion The version of PowerShell required by the module. The version specified or a later version must be installed for the module to work.

RequiredAssemblies A list of .NET assemblies that must be loaded for the module to work.

TypesToProcess A list of TYPES.PS1XML files loaded by the

module to create custom data types for the module’s cmdlets.

Although PowerShell includes a New-Module cmdlet for creating modules, you’ll more commonly use Get-Module, Import-Module, and Remove-Module to work with existing modules. You can list the available modules by entering get-module

-listavailable. However, this will give you the full definition of each module in list

format. A better way to find available modules is to look for them by name, path, and description:

get-module -listavailable | format-list name, path, description

You can also look for them only by name and description:

If you want to determine the availability of a specific module, enter the following command:

get-module -listavailable [-name] ModuleNames

where ModuleNames is a comma-separated list of modules to check. You can enter module names with or without the associated file extension and use wildcards such as. Note that when you use the –ListAvailable parameter, the –Name parameter is position sensitive, allowing you to specify modules using either

get-module –listavailable –name ModuleNames

or

get-module –listavailable ModuleNames

Here is an example:

get-module –listavailable –name networkloadbalancingclusters

The core set of modules available in PowerShell depends on the versions of Windows you are running as well as the components that are installed. Table 3-7 lists some of the most common modules as well as the operating systems they are commonly found on by default.

TABLE 3-7 Common PowerShell Modules

NAME DESCRIPTION

OPERATING SYSTEM

ActiveDirectory Provides a comprehensive set of cmdlets for working with Active Directory Domain Services (AD DS).

Windows Server 2008 Release 2 or later

ADRMS Provides cmdlets for updating,

installing, and uninstalling Active Directory Rights Management Services (AD RMS), including Update-ADRMS, Uninstall-ADRMS, Install-ADRMS.

Windows Server 2008 Release 2 or later

BestPractices Provides cmdlets for testing best-practices scenarios, including Get-BPAModel, Invoke-BPAModel, Get-BPAResult, Set-BPAResult.

Windows Server 2008 Release 2 or later

FailoverClusters Provides a comprehensive set of cmdlets for working with Microsoft Cluster Service.

Windows Server 2008 Release 2 or later

TABLE 3-7 Common PowerShell Modules

NAME DESCRIPTION

OPERATING SYSTEM

FileTransfer Provides cmdlets for working with Background Intelligent Transfer Service, including Add-FileTransfer, Clear-FileTransfer, Complete- FileTransfer, Get-FileTransfer, New- FileTransfer, Resume-FileTransfer Set-FileTransfer, Suspend-FileTransfer.

Windows Vista or later

GroupPolicy Provides a comprehensive set of cmdlets for working with Group Policy objects (GPOs).

Windows Server 2008 Release 2 or later NetworkLoadBalancing-

Clusters

Provides a comprehensive set of cmdlets for working with Network Load Balancing (NLB) clusters.

Windows Server 2008 Release 2 or later PSDiagnostics Provides functions for performing

event traces, including Disable- PSTrace, Disable-PSWSMan- CombinedTrace, Disable- WSManTrace, Enable-PSTrace, Enable-PSWSManCombinedTrace, Enable-WSManTrace, Get- LogProperties, Set-LogProperties, Start-Trace, Stop-Trace. Windows Vista or later

RemoteDesktopServices Provides cmdlets for working with Terminal Services running in Remote Desktop mode.

Windows Server 2008 Release 2 or later ServerManager Provides cmdlets for listing, adding,

and removing Windows features, including Get-WindowsFeature, Add-WindowsFeature, Remove- WindowsFeature. Windows Server 2008 Release 2 or later

TroubleshootingPack Provides cmdlets for getting infor- mation about and running trouble- shooting packs you’ve installed, including Get-TroubleshootingPack and Invoke-TroubleshootingPack.

Windows 7 or later

WebAdministration Provides a comprehensive set of cmdlets for working with Internet Information Services (IIS).

Windows Server 2008 Release 2 or later

The components for available modules are registered in the operating system as necessary but are not added to your PowerShell sessions by default (in most instances). Therefore, to use functions, cmdlets, or other features of a module, you must fi rst import the module. Modules such as PSDiagnostics that defi ne functions and include .PSM1 fi les require an execution policy to be set so that signed scripts can run.

You can import an available module into the current session by using the Import-Module cmdlet. For example, to import the WebAdminstration module, type import-module webadministration. After you import a module, its provid- ers, cmdlets, and other features are available in the console session.

If you add the necessary Import-Module commands to a relevant profi le, you can be sure that modules you want to use are always loaded. To fi nd imported modules or to verify that an additional module is imported, enter the following command:

get-module | format-table name, description

Any module listed in the output is imported and available.

To remove a module from the current session, use the Remove-Module cmdlet. For example, to remove the WebAdministration module from the current session, type remove-module webadministration. The module is still loaded, but the pro- viders, cmdlets, and other features that it supports are no longer available.

You will often want to be sure that a particular module has been imported before you try to use its features. In the following example, when the WebAdministration module is available, the statement in parentheses evaluates to True, and any code in the related script block is executed:

if (get-module -name WebAdministration -erroraction silentlycontinue) {

Code to execute if the provider is available. } else {

Code to execute if the provider is not available. }

As shown previously, you could add an Else clause to defi ne alternative actions. As before, I set the –ErrorAction parameter to SilentlyContinue so that error mes- sages aren’t written to the output if the module has not been imported.

if (get-module -name WebAdministration -erroraction silentlycontinue) {

Code to execute if the provider is available. } else {

Code to execute if the provider is not available. }

REAL WORLD Although checking for modules is helpful, you’ll want to consider the case of SQL Server separately. The SQL Server PowerShell console loads an extended environment designed specifi cally for working with SQL Server. You can re-create this environment using a lengthy script that loads all the right extensions. However, it usu- ally is much easier to simply start the SQL Server PowerShell console when you want to manage SQL Server using PowerShell.

Generally, if the $sqlpsreg variable exists and has child items, the user is running the SQL Server PowerShell console. Knowing this, you can determine whether this console is available as shown in the following example:

if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue") { throw "SQL Server PowerShell is not installed."

} else {

$item = Get-ItemProperty $sqlpsreg

$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path) }

Here, you determine whether the $sqlpsreg variable exists and has child items. If the variable doesn’t exist, PowerShell throws an error. If the variable exists, you get the properties of the related object and then use the Path property to specify the path to use with SQL Server.

In document Windows PowerShell 2.0 (Page 93-98)