All posts by Adam

about_WMI_Cmdlets

TOPIC
    about_WMI_Cmdlets

SHORT DESCRIPTION
    Provides background information about Windows Management Instrumentation
    (WMI) and Windows PowerShell.

LONG DESCRIPTION
    This topic provides information about WMI technology, the WMI cmdlets for
    Windows PowerShell, WMI-based remoting, WMI accelerators,
    and WMI troubleshooting. This topic also provides links to more information
    about WMI.

About WMI

     Windows Management Instrumentation (WMI) is the Microsoft implementation
     of Web-Based Enterprise Management (WBEM), which is an industry
     initiative to develop a standard technology for accessing management
     information in an enterprise Environment. WMI uses the Common Information
     Model (CIM) industry standard to represent systems, applications,
     networks, devices, and other managed components. CIM is developed and
     maintained by the Distributed Management Task Force (DMTF). You can use
     WMI to manage both local and remote computers. For example, you can use
     WMI to do the following:

         — Start a process on a remote computer.

         — Restart a computer remotely.

         — Get a list of the applications that are installed on a local or
             remote computer.

         — Query the Windows event logs on a local or remote computer.

The WMI Cmdlets for Windows PowerShell

     Windows PowerShell implements WMI Functionality through a set of cmdlets
     that are available in Windows PowerShell by default. You can use these
     cmdlets to complete the end-to-end tasks necessary to manage local and
     remote computers.

     The following WMI cmdlets are included.

     Cmdlet                 Description
     ——————     ———————————————-
     Get-WmiObject         Gets instances of WMI classes or information
                             about the available classes.

     Invoke-WmiMethod     Calls WMI methods.

     Register-WmiEvent     Subscribes to a WMI event.

     Remove-WmiObject     Deletes WMI classes and instances.

     Set-WmiInstance        Creates or modifies instances of WMI classes.

Sample Commands

     The following command displays the BIOS information for the local
     computer.

         C:\PS> Get-WmiObject win32_bios | Format-List *

     The following command displays information about the WinRM service
     for three remote computers.

         C:\PS> Get-WmiObject -query “select * from win32_service where name=’WinRM'” -computername server01, server01, server03

     The following more complex command exits all instances of a program.

         C:\PS> notepad.exe
         C:\PS> $np = Get-WmiObject -query “select * from win32_process where name=’notepad.exe'”
         C:\PS> $np | Remove-WmiObject

WMI-Based Remoting

     While the ability to manage a local system through WMI is useful, it is
     the remoting capabilities that make WMI a powerful administrative tool.
     WMI uses Microsoft’s Distributed Component Object Model (DCOM) to
     connect to and manage systems. You might have to configure some systems
     to allow DCOM connections. Firewall settings and locked-down DCOM
     permissions can block WMI’s ability to remotely manage systems.

WMI Type Accelerators

     Windows PowerShell includes WMI type accelerators. These WMI type
     accelerators (shortcuts) allow more direct access to a WMI objects
     than a non-type accelerator approach would allow.

     The following type accelerators are supported with WMI:

         [WMISEARCHER] – A shortcut for searching for WMI objects.

         [WMICLASS] – A shortcut for accessing the static properties
                     and methods of a class.

         [WMI] – A shortcut for getting a single instance of a class.

     [WMISEARCHER] is a type accelerator for a ManagementObjectSearcher.
     It can take a string constructor to create a searcher that you can then
     do a GET() on.

     For example:

     PS> $s = [WmiSearcher]’Select * from Win32_Process where Handlecount > 1000′
     PS> $s.Get() |sort handlecount |ft handlecount,__path,name -auto

     handlecount __PATH                                             name
     ———– ——                                             —-
     1105         \\SERVER01\root\cimv2:Win32_Process.Handle=”3724″ powershell…
     1132         \\SERVER01\root\cimv2:Win32_Process.Handle=”1388″ winlogon.exe
     1495         \\SERVER01\root\cimv2:Win32_Process.Handle=”2852″ iexplore.exe
     1699         \\SERVER01\root\cimv2:Win32_Process.Handle=”1204″ OUTLOOK.EXE
     1719         \\SERVER01\root\cimv2:Win32_Process.Handle=”1912″ iexplore.exe
     2579         \\SERVER01\root\cimv2:Win32_Process.Handle=”1768″ svchost.exe

     [WMICLASS] is a type accelerator for ManagementClass. This has a
     string constructor that takes a local or absolute WMI path to a WMI
     class and returns an object that is bound to that class.

     For example:

     PS> $c = [WMICLASS]”root\cimv2:WIn32_Process”
     PS> $c |fl *
     Name             : Win32_Process
     __GENUS         : 1
     __CLASS         : Win32_Process
     __SUPERCLASS     : CIM_Process
     __DYNASTY        : CIM_ManagedSystemElement
     __RELPATH        : Win32_Process
     __PROPERTY_COUNT : 45
     __DERIVATION     : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemElement}
     __SERVER         : SERVER01
     __NAMESPACE     : ROOT\cimv2
     __PATH         : \\SERVER01\ROOT\cimv2:Win32_Process

     [WMI] is a type accelerator for ManagementObject. This has a string
     constructor that takes a local or absolute WMI path to a WMI instance
     and returns an object that is bound to that instance.

     For example:

     PS> $p = [WMI]’\\SERVER01\root\cimv2:Win32_Process.Handle=”1204″‘
     PS> $p.Name
     OUTLOOK.EXE

WMI Troubleshooting

     The following problems are the most common problems that might occur
     when you try to connect to a remote computer.

    Problem 1: The remote computer is not online.

     If a computer is offline, you will not be able to connect to it by
     using WMI. You may receive the following error message:

         “Remote server machine does not exist or is unavailable”

     If you receive this error message, verify that the computer is online.
     Try to ping the remote computer.

    Problem 2: You do not have local administrator rights on the remote
             computer.

     To use WMI remotely, you must have local administrator rights on the
     remote computer. If you do not, access to that computer will be denied.

     To verify namespace security:

         a. Click Start, right-click My Computer, and then click Manage.

         b. In Computer Management, expand Services and Applications,
             right-click WMI Control, and then click Properties.

         c. In the WMI Control Properties dialog box, click the Security tab.

    Problem 3: A firewall is blocking access to the remote computer.

     WMI uses the DCOM (Distributed COM) and RPC (Remote Procedure Call)
     protocols to traverse the network. By default, many firewalls block
     DCOM and RPC traffic. If your firewall is blocking these protocols,
     your connection will fail. For example, Windows Firewall in Microsoft
     Windows XP Service Pack 2 is configured to automatically block all
     unsolicited network traffic, including DCOM and WMI. In its default
     configuration, Windows Firewall rejects an incoming WMI request, and
     you receive the following error message:

         “Remote server machine does not exist or is unavailable”

More Information about WMI

     For more information about WMI, see the following topics in the MSDN
     (Microsoft Developer Network) library:

         “About WMI:
         http://go.microsoft.com/fwlink/?LinkId=142212

         “WMI Troubleshooting”
         http://go.microsoft.com/fwlink/?LinkId=142213

     And, see “Secrets of Windows Management Instrumentation – Troubleshooting
     and Tips” in the Microsoft TechNet Script Center:

         http://go.microsoft.com/fwlink/?LinkId=142214

SEE ALSO
    Online version: http://go.microsoft.com/fwlink/?LinkId=142219
    Get-WmiObject
    Invoke-WmiMethod
    Register-WmiEvent
    Remove-WmiObject
    Set-WmiInstance

about_Windows_PowerShell_ISE

TOPIC
    about_Windows_PowerShell_ISE

SHORT DESCRIPTION
    Describes the features and system requirements of Windows PowerShell
    Integrated Scripting Environment (ISE).

LONG DESCRIPTION
    Windows PowerShell ISE is a host application for Windows PowerShell.
    In Windows PowerShell ISE, you can run commands and write, test, and debug
    scripts in a single Windows-based graphical user interface. Its features
    include multiline editing, tab completion, syntax coloring, selective
    execution, context-sensitive Help, and support for right-to-left languages.

    Notes: Because this feature requires a user interface, it does not work on
         Server Core installations of Windows Server.

         Window PowerShell ISE is built on the Windows Presentation
         Foundation (WPF). If the graphical elements of Windows PowerShell
         ISE do not render correctly on your system, you might resolve the
         problem by adding or adjusting the graphics rendering settings on
         your system. This might be required if the computer has an older
         video driver or you are using virtualization software. For more
         information, see “Graphics Rendering Registry Settings” in the MSDN
         library at http://go.microsoft.com/fwlink/?LinkId=144711.

Running Interactive Commands

    You can run any Windows PowerShell expression or command in Windows
    PowerShell ISE. You can use cmdlets, providers, snap-ins, and modules as
    you would use them in the Windows PowerShell console.

    You can type or paste interactive commands in the Command pane. To run the
    commands, you can use buttons, menu items, and keyboard shortcuts.

    You can use the multiline editing feature to type or paste several lines
    of code into the Command pane at once. When you press the UP ARROW key to
    recall the previous command, all the lines in the command are recalled.
    When you type commands, press SHIFT+ENTER to make a new blank line appear
    under the current line.

Viewing Output

    The results of commands and scripts are displayed in the Output pane. You
    can move or copy the results from the Output pane by using keyboard
    shortcuts or the Output toolbar, and you can paste the results in other
    programs. You can also clear the Output pane by clicking the Clear Output
    button or by typing one of the following commands:

        clear-host

        cls

Writing Scripts and Functions

    In the Script pane, you can open, compose, edit, and run scripts. The
    Script pane lets you edit scripts by using buttons and keyboard shortcuts.
    You can also copy, cut, and paste text between the Script pane and the
    Command pane.

    You can use the selective run feature to run all or part of a script. To
    run part of a script, select the text you want to run, and then click the
    Run Script button. Or, press F5.

Debugging Scripts

    You can use the Windows PowerShell ISE debugger to debug a Windows
    PowerShell script or Function. When you debug a script, you can use menu
    items and shortcut keys to perform many of the same tasks that you would
    perform in the Windows PowerShell console. For example, to set a line
    breakpoint in a script, right-click the line of code, and then click
    Toggle Breakpoint.

    You can also use the Windows PowerShell debugger cmdlets in the Command
    pane just as you would use them in the console.

Tab Completion

    Windows PowerShell ISE has tab completion for cmdlet names, parameter
    names, and Microsoft .NET Framework static types. To use tab completion,
    type the beginning of the name, and then press the TAB key.

Getting Help

    Windows PowerShell ISE includes a searchable compiled Help file that
    describes Windows PowerShell ISE and Windows PowerShell. This Help file
    includes all the Help that is available from the Get-Help cmdlet. To view
    the Help file in Windows PowerShell ISE, use the Help menu. Or, press F1.

    The Help is context sensitive. For example, if you type Invoke-Item and
    then press F1, the Help file opens to the Help topic for the Invoke-Item
    cmdlet.

    And, you can use the Get-Help cmdlet in Windows PowerShell as you would in
    the Windows PowerShell console.

Customizing the View

    You can use Windows PowerShell ISE features to move and to resize the
    Command pane, the Output pane, and the Script pane. You can show and hide
    the Script pane, and you can change the text size in all the panes.

    You can also use the $Host Variable to change some aspects of the
    appearance of Windows PowerShell ISE, including the window title and the
    foreground and background colors in the Output pane. In addition, Windows
    PowerShell ISE has its own custom host Variable, $psgHost. You can use
    this Variable to customize Windows PowerShell ISE, including adding menus
    and menu items.

Windows PowerShell ISE Profile

    Windows PowerShell ISE has its own Windows PowerShell profile,
    Microsoft.PowerShellISE_profile.ps1. In this profile, you can store
    Functions, Aliases, Variables, and commands that you use in Windows
    PowerShell ISE.

    Items in the Windows PowerShell AllHosts profiles (CurrentUser\AllHosts
    and AllUsers\AllHosts) are also available in Windows PowerShell ISE, just
    as they are in any Windows PowerShell host program. However, the items
    in your Windows PowerShell console profiles are not available in Windows
    PowerShell ISE.

    Instructions for moving and reconfiguring your profiles are available in
    Windows PowerShell ISE Help and in about_profiles.

System Requirements

    -Operating Systems:
         – Windows 7
         – Windows Server 2008
         – Windows Server 2003 with Service Pack 2
         – Windows Vista with Service Pack 1
         – Windows XP with Service Pack 2

    – Microsoft .NET Framework 3.0

    – Windows PowerShell remoting requires Windows Remote Management 2.0.

Notes

    – The Get-WinEvent cmdlet requires Windows Vista and later versions of
     Windows and the Microsoft .NET Framework 3.5.

    – The Export-Counter cmdlet runs only in Windows 7.

Starting Windows PowerShell ISE

    – To start Windows PowerShell ISE, click Start, point to All Programs,
     point to Windows PowerShell, and then click Windows PowerShell ISE.

    – In the Windows PowerShell console, Cmd.exe, or in the Run box,
     type “powershell_ise.exe”.

SEE ALSO
    about_profiles
    Get-Help

about_Windows_PowerShell_2.0

TOPIC
    about_Windows_PowerShell_2.0

SHORT DESCRIPTION
    Describes the new features that are included in Windows PowerShell 2.0.

LONG DESCRIPTION
    Windows PowerShell 2.0 includes several significant features that
    extend its use, improve its usability, and allow you to control and
    manage Windows-based Environments more easily and comprehensively.

    Windows PowerShell 2.0 is backward compatible. Cmdlets, providers,
    snap-ins, scripts, Functions, and profiles that were designed for Windows
    PowerShell 1.0 work in Windows PowerShell 2.0 without changes.

NEW FEATURES
    Windows PowerShell 2.0 includes the following new features.

Remoting

     Windows PowerShell 2.0 lets you run commands on one or many remote
     computers with a single Windows PowerShell command. You can run
     individual commands, or you can create a persistent connection
     (a session) to run a series of related commands. You can also start a
     session with a remote computer so that the commands you type run
     directly on the remote computer.

     The remoting features of Windows PowerShell are built on Windows
     Remote Management (WinRM). WinRM is the Microsoft implementation of
     the WS-Management protocol, a standard SOAP-based, firewall-compatible
     communications protocol.

     The remote computers must have Windows PowerShell 2.0, the Microsoft .NET
     Framework 2.0, and the WinRM service. Remote commands are supported
     on all operating systems that can run Windows PowerShell. The
     current user must have permission to run commands on the remote
     computers. For more information, see about_remote_requirements.

     To support remoting, the Invoke-Command, Enter-PSSession, and
     Exit-PSSession cmdlets have been added, along with other cmdlets
     that contain the PSSession noun. These cmdlets let you create and manage
     persistent connections.

     The ComputerName parameter has also been added to several cmdlets,
     including the Get-Process, Get-Service, and Get-Eventlog cmdlets. This
     parameter allows you to get information about remote computers.
     These cmdlets use .NET Framework methods to get their data,
     so they do not rely on Windows PowerShell remoting. They do not require
     any new programs or configuration. For more information, see the Help for
     each cmdlet.

     For more information about remote commands, see about_remote and
     about_remote_FAQ. For more information about sessions, see
     about_pssessions.

Windows PowerShell ISE

     Windows PowerShell 2.0 includes Windows PowerShell Integrated
     Scripting Environment (ISE), a host application that lets you run
     commands, and design, write, test, and debug scripts in a graphical,
     color-coded, Unicode-based Environment.

     Windows PowerShell ISE requires the Microsoft .NET Framework 3.0 or
     later.

     Windows PowerShell ISE includes:

     – A Command pane that lets you run interactive commands just as you
         would in the Windows PowerShell console. Just type a command, and then
         press ENTER. The output appears in the Output pane.

     – A Script pane that lets you compose, edit, debug, and run Functions
         and scripts.

     – Multiple tabs, each with its own Command and Script pane, that let you
         work on one or several tasks independently.

     Windows PowerShell ISE is designed for both novice and advanced users.

Background Jobs

     Background jobs are commands that run asynchronously. When you run a
     background job, the command prompt returns immediately, even if the
     command is still running. You can use the background job feature to run a
     complex command in the background so that you can use your session for
     other work while the command runs.

     You can run a background job on a local or remote computer and then save
     the results on the local or remote computer. To run a job remotely, use
     the Invoke-Command cmdlet.

     Windows PowerShell includes a set of cmdlets that contain the Job noun
     (the Job cmdlets). Use these cmdlets for creating, starting, managing,
     and deleting background jobs and for getting the results of a background
     job. To get a list of the job cmdlets, type the following command:

         Get-Command *-job

     For more information about background jobs, see about_jobs.

Script Debugger

     Windows PowerShell 2.0 includes a cmdlet-based debugger for scripts and
     Functions. The debugger is supported by a fully documented public API
     that you can use to build your own debugger or to customize or extend
     the debugger.

     The debugger cmdlets let you set breakpoints on lines, columns,
     Variables, and commands. These cmdlets let you manage the breakpoints
     and display the call stack. You can create conditional breakpoints and
     specify custom actions at a breakpoint, such as running diagnostic and
     logging scripts.

     When you reach a breakpoint, Windows PowerShell suspends execution
     and starts the debugger. The debugger includes a set of custom commands
     that let you step through the code. You can also run standard Windows
     PowerShell commands to display the values of Variables, and you can use
     cmdlets to investigate the results.

     For more information about debugging, see about_debuggers.

Data Section

     Scripts designed for Windows PowerShell 2.0 can have one or more
     DATA sections that isolate the data from the script logic. The data in
     the new DATA section is restricted to a specified subset of the Windows
     PowerShell scripting language.

     In Windows PowerShell 2.0, the DATA section is used to support
     script internationalization. You can use the DATA section to isolate
     and identify user message strings that will be translated into
     multiple user interface languages.

     For more information, see about_data_sections.

Script Internationalization

     Windows PowerShell 2.0 script internationalization features allow you
     to better serve users throughout the world. Script internationalization
     enables scripts and Functions to display messages and Help text to users
     in multiple languages.

     The script internationalization features query the operating system user
     interface culture ($PsUICulture) during execution and then import the
     appropriate translated text strings so you can display them to the user.
     The Data section lets you store text strings separate from code so that
     they are easily identified. A new cmdlet, ConvertFrom-StringData,
     converts text strings into dictionary-like hash tables to facilitate
     translation.

     For more information, see about_script_internationalization.

WMI Cmdlets

     The Windows Management Instrumentation (WMI) Functionality of
     Windows PowerShell 2.0 is improved with the addition of the following
     cmdlets:

         – Remove-WmiObject
         – Set-WmiInstance
         – Invoke-WmiMethod

     New parameters have been added to the Get-WmiObject cmdlet. All the WMI
     cmdlets now support the following parameters:

         – EnableAllPrivileges
         – Impersonation
         – Authentication
         – Authority

     These new parameters give you more refined control over the security
     configuration of your WMI operations without requiring you to work
     directly with the types in the .NET Framework Class Library.

     For a list of WMI cmdlets, type the following command:

         Get-Help *wmi*

     To get help for each cmdlet, type Get-Help followed by the cmdlet name.

The Get-WinEvent Cmdlet

     The Get-WinEvent cmdlet gets events from Event Viewer logs and from
     Event Tracing for Windows (ETW) event log files on local and remote
     computers. It can get events from classic event logs and from the
     Windows Event Logs that were introduced in Windows Vista.

     You can use Get-WinEvent to get the objects that represent event logs, event
     log providers, and the events in the logs. Get-WinEvent lets you combine
     events from different sources in a single command. It supports
     advanced queries in XML Path Language (XPath), XML, and hash table
     format.

     Get-WinEvent requires Windows Vista or Windows Server 2008 and the
     Microsoft .NET Framework 3.5.

The Out-GridView Cmdlet

     The Out-GridView cmdlet displays the results of other commands in an
     interactive table in which you can search, sort, group, and filter the
     results. For example, you can send the results of a Get-Process,
     Get-WmiObject, Get-WinEvent, or Get-Eventlog command to Out-GridView and
     then use the table features to examine the data.

        help Out-GridView -full

The Add-Type Cmdlet

     The Add-Type cmdlet lets you add .NET Framework types to
     Windows PowerShell from the source code of another .NET Framework
     language.

     Add-Type compiles the source code that creates the types and generates
     assemblies that contain the new .NET Framework types. Then, you can use
     the .NET Framework types in Windows PowerShell commands along with the
     standard object types provided by the .NET Framework.

     You can also use Add-Type to load assemblies into your session so that
     you can use the types in the assemblies in Windows PowerShell.

     Add-Type allows you develop new .NET Framework types, to
     use .NET Framework types in C# libraries, and to access Win32 APIs.

     For more information, see Add-Type.

Event Notification

     Windows PowerShell 2.0 introduces event notification. Users can register
     and subscribe to events, such as Windows PowerShell events, WMI events,
     or .NET Framework events. And, users can listen, forward, and act on
     management and system events both synchronously and asynchronously.

     Developers can write applications that use the event architecture
     to receive notification about state changes. Users can write
     scripts that subscribe to various events and that react to the content.

     Windows PowerShell provides cmdlets that create new events, get
     events and event subscriptions, register and unregister events,
     wait for events, and delete events. For more information about these
     cmdlets, type the following command:

         Get-Command *-event

Modules

     Windows PowerShell modules let you divide and organize your
     Windows PowerShell scripts into independent, self-contained,
     reusable units. Code from a module executes in its own context,
     so it does not add to, conflict with, or overwrite the Variables,
     Functions, Aliases, and other resources in the session.

     You can write, distribute, combine, share, and reuse modules to build
     simple scripts and complex applications.

     Windows PowerShell 2.0 includes cmdlets to add, get, and remove modules
     and to export module members. For more information about the cmdlets
     that are related to modules, type the following command:

         Get-Command *-module*

Transactions

     Windows PowerShell 2.0 includes support for transactions. Transactions
     let you undo an entire series of operations. Transactions are available
     only for operations that support transactions. They are designed for
     applications that require atomicity, consistency, isolation, and
     recoverability, like databases and message queuing.

     Cmdlets and providers that support transactions have a new
     UseTransaction parameter. To start an operation within a transaction,
     use the Start-Transaction cmdlet. Then, when you use the cmdlets that
     perform the operation, use the UseTransaction parameter of each cmdlet
     when you want the command to be part of a transaction.

     If any command in the transaction fails at any point, use the
     Rollback-Transaction cmdlet to undo all the commands in the transaction.
     If all the commands succeed, use the Commit-Transaction cmdlet to make
     the command actions permanent.

     Windows PowerShell 2.0 includes cmdlets to start, use, commit, and roll
     back transactions. For information about these cmdlets, type the
     following command:

         Get-Command *transaction*

Breaking Changes to Windows PowerShell 1.0

     — The value of the PowerShellVersion Registry entry in
        HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine
        is changed to 2.0.

     — New cmdlets and Variables have been added. These additions might
     conflict with Variables and Functions in profiles and scripts.

     — The -IEQ operator performs a case insensitive comparison on characters.

     — The Get-Command cmdlet gets Functions by default, in addition to
        cmdlets.

     — Native commands that generate a user interface cannot be piped to the
        Out-Host cmdlet.

     — The new Begin, Process, End, and Dynamic Param language keywords might
        conflict with similar words used in scripts and Functions. Interpreting
        these words as language keywords might result in parsing errors.

     — Cmdlet name resolution has changed. In Windows PowerShell 1.0, a
        runtime error was generated when two Windows PowerShell snap-ins
        exported cmdlets with the same name. In Windows PowerShell 2.0, the
        last cmdlet that is added to the session runs when you type the command
        name. To run a command that does not run by default, qualify the cmdlet
        name with the name of the snap-in or module in which it originated.

     — A Function name followed by ‘-?’ gets the help topic for the Function,
        if one is included in the Function.

    — Parameter resolution for Microsoft .Net Frameword methods have changed.
        In Windows PowerShell 1.0, if you called an overloaded .NET method
        that has more than one best fit syntax, no error was reported. In
        Windows PowerShell 2.0, an ambiguity error is reported.

        In addition, in Windows PowerShell 2.0, the algorithm for choosing the
        best fit method has been revised significantly to minimize the number
        of ambiguities.

     — If you are enumerating a collection in the pipeline and you try to
        modify the collection in the pipeline, Windows PowerShell throws an
        exception.

        For example, the following commands would work in Windows
        PowerShell 1.0, but would fail after first pipeline iteration in
        Windows PowerShel 2.0.

            $h = @{Name=”Hello”; Value=”Test”}
            $h.keys | ForEach-Object {$h.remove($_)}

        To avoid this error, create a sub-expression for the enumerator
        by using the $() characters. For example:

        $($h.keys) | ForEach-Object {$h.remove($_)}

    For more information about Windows PowerShell 2.0, visit the following Web
    sites:

    — Windows PowerShell Web Site
     http://go.microsoft.com/fwlink/?LinkID=106031

    — Windows PowerShell Team Blog:
     http://go.microsoft.com/fwlink/?LinkId=143696

SEE ALSO
    about_data_sections
    about_debuggers
    about_functions_advanced
    about_jobs
    about_join
    about_pssessions
    about_remote
    about_script_internationalization
    about_split

about_wildcards

TOPIC
    about_wildcards

SHORT DESCRIPTION
    Describes how to use wildcard characters in Windows PowerShell.

LONG DESCRIPTION
    In many cases, you will want to run a cmdlet against a group of
    items rather than an individual item. For example, you might
    want to locate all the files in the C:\Techdocs directory that have a
    .ppt file name extension. If you were to run the following command, it
    would return all the items in the directory:

        Get-ChildItem c:\techdocs

    The problem with this command is that you would have to visually
    inspect all the documents listed in the directory to determine which
    files use the .ppt file name extension. However, you can limit the items
    that are returned by using wildcard characters in a cmdlet’s parameters.
    A wildcard character is a type of placeholder that allows you to search
    unknown values in order to return specific results. The process of using
    wildcard characters is sometimes referred to as “globbing”. For example,
    you can recast the previous example so that only .ppt files are
    returned:

        Get-ChildItem c:\techdocs\*.ppt

    In this case, the asterisk (*) is used as a wildcard character to specify
    that any characters can exist before the .ppt file name extension. Because
    the file name extension is included, all files returned by the command must
    have that file name extension, but the files can have any name. As a
    result, only the files that you are looking for are returned.

    Windows PowerShell supports several wildcard characters in addition to the
    asterisk wildcard character.

        Wildcard Description        Example Match             No match
        ——– —————— ——– —————– ——–
        *        Matches zero or    a*     A, ag, Apple     banana
                 more characters

        ?        Matches exactly    ?n     an, in, on        ran
                 one character in
                 the specified
                 position

        [ ]     Matches a range    [a-l]ook book, cook, look took
                 of characters

        [ ]     Matches specified [bc]ook book, cook        hook
                 characters

    Most cmdlets accept wildcard characters in some of their parameters. The
    Help topic for each cmdlet describes which parameters, if any, permit
    wildcard characters. For parameters in which wildcard characters are
    accepted, their use is case insensitive. For example, ?n will return An,
    an, In, in, On, and on.

    You can also mix wildcard characters within a single parameter. For
    example, suppose that you want to display all the .txt files in the
    C:\Techdocs directory that begin with the letters a through l. You can use
    the following command:

        Get-ChildItem c:\techdocs\[a-l]*.txt

    The command uses a range wildcard ([a-l]) to specify that the file name
    should begin with the letters a through l. The command then uses the
    asterisk wildcard character to provide a placeholder for any characters
    between the first letter and the file name extension.

SEE ALSO
    about_Language_Keywords

about_While

TOPIC
    about_While

SHORT DESCRIPTION
    Describes a language statement that you can use to run a command block
    based on the results of a conditional test.

LONG DESCRIPTION
    The While statement (also known as a While loop) is a language construct
    for creating a loop that runs commands in a command block as long as a
    conditional test evaluates to true. The While statement is easier to
    construct than a For statement because its syntax is less complicated.
    In addition, it is more flexible than the Foreach statement because you
    specify a conditional test in the While statement to control how many times
    the loop runs.

    The following shows the While statement syntax:

        while (<condition>){<statement list>}

    When you run a While statement, Windows PowerShell evaluates
    the <condition> section of the statement before entering the
    <statement list> section. The condition portion of the statement resolves
    to either true or false. As long as the condition remains true, Windows
    PowerShell reruns the <statement list> section.

    The <statement list> section of the statement contains one or more commands
    that are run each time the loop is entered or repeated.

    For example, the following While statement displays the numbers 1
    through 3 if the $val Variable has not been created or if the $val Variable
    has been created and initialized to 0.

        while($val -ne 3)
        {
            $val++
            Write-Host $val
        }

    In this example, the condition ($val is not equal to 3) is true while
    $val = 0, 1, 2. Each time through the loop, $val is incremented by 1
    using the ++ unary increment operator ($val++). The last time through
    the loop, $val = 3. When $val equals 3, the condition statement
    evaluates to false, and the loop exits.

    To conveniently write this command at the Windows PowerShell command
    prompt, you can enter it in the following way:

        while($val -ne 3){$val++; Write-Host $val}

    Notice that the semicolon separates the first command that adds 1 to
    $val from the second command that writes the value of $val to the
    console.

SEE ALSO
    about_Comparison_Operators
    about_Foreach
    about_For

about_Variables

TOPIC
    about_Variables

SHORT DESCRIPTION
    Describes how Variables store values that can be used in Windows
    PowerShell.

LONG DESCRIPTION
    A Variable is a unit of memory in which values are stored. In Windows
    PowerShell, Variables are represented by single-word text strings that
    begin with the dollar sign ($), such as $a, $process, or
    $my_var.

    There are several different types of Variables in Windows PowerShell.

    — User-created Variables: User-created Variables are created and
     maintained by the user. By default, the Variables that you create at
     the Windows PowerShell command line exist only while the Windows
     PowerShell window is open, and they are lost when you close the window.
     To save a Variable, add it to your Windows PowerShell profile. You can
     also create Variables in scripts with global, script, or local scope.

    — Automatic Variables: Automatic Variables store the state of
     Windows PowerShell. These Variables are created by Windows PowerShell,
     and Windows PowerShell changes their values as required to maintain
     their accuracy. Users cannot change the value of these Variables.
     For example, the $PSHome Variable stores the path to the Windows
     PowerShell installation directory. For more information, a list, and
     a description of the automatic Variables, see about_Automatic_Variables.

    — Preference Variables: Preference Variables store user preferences for
     Windows PowerShell. These Variables are created by Windows PowerShell
     and are populated with default values. Users can change the values of
     these Variables. For example, MaximumHistoryCount determines the maximum
     number of entries in the session history. For more information, a list,
     and a description of the preference Variables, see
     about_preference_variables.

WORKING WITH VariableS

    To list all of the Variables in your Windows PowerShell session, type:

     Get-Variable

    To display the value of any Variable, type the name of the Variable,
    preceded by a dollar sign ($). Windows PowerShell responds by displaying
    its value.

     $<variable-name>

    For example:

        PS> $pshome
        C:\Windows\System32\WindowsPowerShell\v1.0

    To create a new Variable or to change the value of a Variable, use an
    assignment statement in the following format:

        $<variable> = <value>

    For example:

        PS> $my-variable = 1, 2, 3

        or

        PS> $VerbosePreference = “Continue”

    To get an object that represents the Variable, use a Get-Variable
    command, such as:

        PS> Get-Variable pid

    To use a Variable, type the Variable name, including the dollar sign ($),
    in a command or expression. If the command or expression is not enclosed
    in quotation marks or if it is enclosed in double-quotation marks (“), the
    value of the Variable is used in the command or expression. If the command
    is enclosed in single quotation marks, (‘), the Variable name is used in
    the expression.

    For example, the first command finds the value of the $profile Variable,
    which is the path to the Windows PowerShell user profile file. The
    second command opens the file in Notepad.

        PS> $profile
        C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

        PS> Notepad $profile

    You can store any type of object in a Variable, including integers,
    strings, arrays, and hash tables, objects that represent processes,
    services, event logs, and computers.

SAVING VariableS
     Variables that you create are available only in the session in which
     you create them. They are lost when you close your session.

     To save a Variable, add the Variable to your Windows PowerShell profile.
     Variables in a profile are added to every Windows PowerShell session
     that you open.

     For example, to change the value of the $VerbosePreference Variable in
     every Windows PowerShell session, add the following command to your Windows
     PowerShell profile.

     $VerbosePreference = “Continue”

     You can add this command to your profile by opening the profile file in a
     text editor, such as Notepad, or you can use an Add-Content command, like
     the following one.

     The following command adds the new value for the $VerbosePreference Variable
     to the CurrentUser,AllHosts profile.

     Add-Content -path $profile.CurrentUserAllHosts -value ‘$VerbosePreference = “Continue”‘

     For more information about Windows PowerShell profiles, see about_profiles.

Variable NAMES WITH SPECIAL CHARACTERS

    You can use braces to force Windows PowerShell to interpret a
    Variable name literally. This is especially helpful when creating
    or referring to a Variable name that includes special characters,
    such as dashes, periods, colons, and parentheses.

    To create a Variable name that includes a hyphen, enclose the
    Variable name in braces. The following command creates a Variable
    named “save-items”.

        C:\PS> ${save-items} = “a”, “b”, “c”
        C:\PS>${save-items}
        a
        b
        c

    To refer to a Variable name that includes parentheses, enclose
    the Variable name in braces.

    For example, the following command gets the child items in the
    directory stores in the “ProgramFiles(x86)” Environment Variable.

        C:\PS> Get-ChildItem ${env:ProgramFiles(x86)}

    To refer to a Variable name that includes braces, enclose the
    Variable name in braces, and use the backtick (escape) character
    to escape the braces. For example, to create a Variable
    named “this{value}is” with a value of 1, type:

        C:\PS> ${this`{value`}is} = 1
        C:\PS> ${this`{value`}is}
        1

THE Variable: DRIVE

     Windows PowerShell includes a Variable: drive that looks and acts like
     a file system drive, but it contains the Variables in your session.

     To change to the Variable drive, type:

        Set-Location Variable:

         (or “cd Variable:”)

     When in the Variable drive, to list the items (variables) in the
     drive, use the Get-ChildItem cmdlet. For example:

         Get-ChildItem

         (or “dir” or “ls”)

     For more information about the Variable: drive and the Windows
     PowerShell Variable provider, type:

         Get-Help Variable

SEE ALSO
    about_Automatic_Variables
    about_environment_variables
    about_preference_variables
    about_scopes

about_type_operators

TOPIC
    about_type_operators

SHORT DESCRIPTION
    Describes the operators that work with Microsoft .NET Framework types.

LONG DESCRIPTION
    The Boolean type operators (-is and -isnot) tell whether an object is an
    instance of a specified .NET Framework type. The -is operator returns a
    value of TRUE if the type matches and a value of FALSE otherwise.
    The -isnot operator returns a value of FALSE if the type
    matches and a value of TRUE otherwise.

    The -as operator tries to convert the input object to the specified .NET
    Framework type. If it succeeds, it returns the converted object. It if
    fails, it returns nothing. It does not return an error.

    The following table lists the type operators in Windows PowerShell.

    Operator Description                 Example
    ——– ————————    ————————————-
    -is     Returns TRUE when the     C:\PS> (Get-Date) -is [datetime]
             input is an instance        True
             of the specified
             .NET Framework type.

    -isnot    Returns TRUE when the     C:\PS> (Get-Date) -isnot [datetime]
             input is not an instance    False
             of the specified
             .NETFramework type.

    -as     Converts the input to     C:\PS> 12/31/07 -as [datetime]
             the specified             Monday, December 31, 2007 12:00:00 AM
             .NET Framework type.

    The syntax of the type operators is as follows:

        <input> <operator> [.NET type]

    You can also use the following syntax:

        <input> <operator> “.NET type”

    To specify the .NET Framework type, enclose the type name in
    brackets ([ ]), or enter the type as a string, such as [DateTime] or
    “datetime” for System.DateTime. If the type is not at the root of the
    system namespace, specify the full name of the object type. You can omit
    “System.”. For example, to specify System.Diagnostics.Process, enter
    [System.Diagnostics.Process], [Diagnostics.Process], or
    “diagnostics.process”.

    The type operators always return a Boolean value, even if the input is a
    collection of objects. However, when the input is a collection, the type
    operators match the .NET Framework type of the collection. They do not
    match the type of each object, even when all of the objects are of the
    same type.

    To find the .NET Framework type of an object, use the Get-Member cmdlet.
    Or, use the GetType method of all the objects together with the FullName
    property of this method. For example, the following statement gets the
    type of the return value of a Get-Culture command:

        C:\PS> (Get-Culture).gettype().fullname
        System.Globalization.CultureInfo

EXAMPLES
    The following examples show some uses of the Type operators:

        C:\PS> 32 -is [Float]
        False

        C:\PS> 32 -is “int”
        True

        C:\PS> (Get-Date) -is [DateTime]
        True

        C:\PS> “12/31/2007” -is [DateTime]
        False

        C:\PS> “12/31/2007” -is [String]
        True

        C:\PS> (Get-Process powershell)[0] -is [System.Diagnostics.Process]
        True

        C:\PS> (Get-Command Get-Member) -is [System.Management.Automation.CmdletInfo]
        True

    The following example shows that when the input is a collection of objects,
    the matching type is the .NET Framework type of the collection, not the type
    of the individual objects in the collection.

    In this example, although both the Get-Culture and Get-UICulture cmdlets
    return System.Globalization.CultureInfo objects, a collection of these
    objects is a System.Object array.

        C:\PS> (Get-Culture) -is [System.Globalization.CultureInfo]
        True

        C:\PS> (Get-UICulture) -is [System.Globalization.CultureInfo]
        True

        C:\PS> (Get-Culture), (Get-UICulture) -is [System.Globalization.CultureInfo]
        False

        C:\PS> (Get-Culture), (Get-UICulture) -is [Array]
        True

        C:\PS> (Get-Culture), (Get-UICulture) | foreach {$_ -is [System.Globalization.CultureInfo])
        True
        True

        C:\PS> (Get-Culture), (Get-UICulture) -is [Object]
        True

    The following examples show how to use the -as operator.

        C:\PS> “12/31/07” -is [datetime]
        False

        C:\PS> “12/31/07” -as [datetime]
        Monday, December 31, 2007 12:00:00 AM

        C:\PS> $date = “12/31/07” -as [datetime]

        C:\PS>$a -is [datetime]
        True

        C:\PS> 1031 -as [System.Globalization.CultureInfo]

        LCID             Name             DisplayName
        —-             —-             ———–
        1031             de-DE            German (Germany)

    The following example shows that when the -as operator cannot convert the
    input object to the .NET Framework type, it returns nothing.

        C:\PS> 1031 -as [System.Diagnostic.Process]
        C:\PS>

SEE ALSO
    about_operators

about_types.ps1xml

TOPIC
    about_types.ps1xml

SHORT DESCRIPTION
    Explains how the Types.ps1xml files let you extend the Microsoft .NET
    Framework types of the objects that are used in Windows PowerShell.

LONG DESCRIPTION
    The Types.ps1xml file in the Windows PowerShell installation directory
    ($pshome) is an XML-based text file that lets you add properties and
    methods to the objects that are used in Windows PowerShell. Windows
    PowerShell has a built-in Types.ps1xml file that adds several elements
    to the .NET Framework types, but you can create additional Types.ps1xml
    files to further extend the types.

    For example, by default, array objects (System.Array) have a Length
    property that lists the number of objects in the array. However, because
    the name “length” does not clearly describe the property, Windows
    PowerShell adds an Alias property named “Count” that displays the same
    value. The following XML adds the Count property to the System.Array type.

        <Type>
            <Name>System.Array</Name>
            <Members>
                <AliasProperty>
                    <Name>Count</Name>
                    <ReferencedMemberName>
                        Length
                    </ReferencedMemberName>
                </AliasProperty>
            </Members>
        </Type>

    To get the new AliasProperty, use a Get-Member command on any array, as shown
    in the following example.

        Get-Member -inputobject (1,2,3,4)

    The command returns the following results.

    Name         MemberType    Definition
    —-         ———-    ———-
    Count         AliasProperty Count = Length
    Address        Method        System.Object& Address(Int32 )
    Clone         Method        System.Object Clone()
    CopyTo         Method        System.Void CopyTo(Array array, Int32 index):
    Equals         Method        System.Boolean Equals(Object obj)
    Get            Method        System.Object Get(Int32 )
    …

    As a result, you can use either the Count property or the Length property
    of arrays in Windows PowerShell. For example:

    C:\PS> (1, 2, 3, 4).count
    4

    C:\PS> (1, 2, 3, 4).length
    4

Creating New Types.ps1xml Files

     The .ps1xml files that are installed with Windows PowerShell are
     digitally signed to prevent tampering because the formatting can include
     script blocks. Therefore, to add a property or method to a .NET Framework
     type, create your own Types.ps1xml files, and then add them to your
     Windows PowerShell console.

     To create a new file, start by copying an existing Types.ps1xml file. The
     new file can have any name, but it must have a .ps1xml file name
     extension. You can place the new file in any directory that is accessible
     to Windows PowerShell, but it is useful to place the files in the Windows
     PowerShell installation directory ($pshome) or in a subdirectory of the
     installation directory.

     When you have saved the new file, use the Update-TypeData cmdlet to add
     the new file to your Windows PowerShell console. If you want your types
     to take precedence over the types that are defined in the built-in file,
     use the PrependData parameter of the Update-TypeData cmdlet.
     Update-TypeData affects only the current console. To make the change to
     all future consoles, export the console, or add the Update-TypeData
     command to your Windows PowerShell profile.

Types.ps1xml and Add-Member

     The Types.ps1xml files add properties and methods to all the instances
     of the objects of the specified .NET Framework type in the affected
     Windows PowerShell console. However, if you need to add properties or
     methods only to one instance of an object, use the Add-Member cmdlet.

     For more information,see Add-Member.

Example: Adding an Age Member to FileInfo Objects

     This example shows how to add an Age property to file objects
     (System.IO.FileInfo). The age of a file is the difference between
     its creation time and the current time in days.

     It is easiest to use the original Types.ps1xml file as a template
     for the new file. The following command copies the original file to
     a file called MyTypes.ps1xml in the $pshome directory.

         Copy-Item Types.ps1xml MyTypes.ps1xml

     Next, open the Types.ps1xml file in any XML or text editor, such
     as Notepad. Because the Age property is calculated by using a script
     block, find a <ScriptProperty> tag to use as a model for the new Age
     property.

     Copy the XML between the <Type> and </Type> tags of the code to create
     the script property. Then, delete the remainder of the file, except for
     the opening <?xml> and <Types> tags and the closing </Types> tag. You
     must also delete the digital signature to prevent errors.

     Begin with the model script property, such as the following script
     property, which was copied from the original Types.ps1xml file.

         <?xml version=”1.0″ encoding=”utf-8″ ?>
         <Types>
             <Type>
                 <Name>System.Guid</Name>
                    <Members>
                        <ScriptProperty>
                            <Name>Guid</Name>
                            <GetScriptBlock>$this.ToString()</GetScriptBlock>
                        </ScriptProperty>
                    </Members>
             </Type>
         </Types>

     Then, change the name of the .NET Framework type, the name of the
     property, and the value of the script block to create an Age property
     for file objects.

         <?xml version=”1.0″ encoding=”utf-8″ ?>
         <Types>
             <Type>
                 <Name>System.IO.FileInfo</Name>
                    <Members>
                        <ScriptProperty>
                            <Name>Age</Name>
                            <GetScriptBlock>
                             ((Get-Date) – ($this.creationtime)).days
                            </GetScriptBlock>
                        </ScriptProperty>
                    </Members>
             </Type>
         </Types>

     After you save the file and close it, use an Update-TypeData command,
     such as the following command, to add the new Types.ps1xml file to the
     current console. The command uses the PrependData parameter to place the
     new file in a higher precedence order than the original file. (For more
     information about Update-TypeData, see Update-TypeData.)

         Update-TypeData -prependpath $pshome\MyTypes.ps1xml

     To test the change, use a Get-ChildItem command to get the
     PowerShell.exe file in the $pshome directory, and then pipe the file to
     the Format-List cmdlet to list all of the properties of the file. As a
     result of the change, the Age property appears in the list.

        Get-ChildItem $pshome\powershell.exe | Format-List -property *

        PSPath            : Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS…
        PSParentPath     : Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS…
        PSChildName     : powershell.exe
        PSDrive         : C
        PSProvider        : Microsoft.PowerShell.Core\FileSystem
        PSIsContainer     : False
        Age             : 16
        VersionInfo     : File:             C:\WINDOWS\system32\WindowsPow…
                    InternalName:     POWERSHELL
                    OriginalFilename: PowerShell.EXE
    …

     You can also display the Age property of the file by using the following
     command.

     (Get-ChildItem $pshome\powershell.exe).age
         16

The XML in Types.ps1xml Files

     The <Types> tag encloses all of the types that are defined in the file.
     There should be only one pair of <Types> tags.

     Each .NET Framework type mentioned in the file should be represented by
     a pair of <Type> tags.

     The type tags must contain the following tags:

         <Name>: A pair of <Name> tags that enclose the name of the affected
                 .NET Framework type.

         <Members>: A pair of <Members> tags that enclose the tags for the
                     new properties and methods that are defined for the
                     .NET Framework type.

     Any of the following member tags can be inside the <Members> tags.

     <AliasProperty>: Defines a new name for an existing property.

         The <AliasProperty> tag must have a pair of <Name> tags that specify
         the name of the new property and a pair of <ReferencedMemberName> tags
         that specify the existing property.

         For example, the Count Alias property is an Alias for the Length
         property of array objects.

             <Type>
                 <Name>System.Array</Name>
                 <Members>
                     <AliasProperty>
                         <Name>Count</Name>
                         <ReferencedMemberName>Length</ReferencedMemberName>
                     </AliasProperty>
                 </Members>
             </Type>

     <CodeMethod>: References a static method of a .NET Framework class.

         The <CodeMethod> tag must have a pair of <Name> tags that specify
         the name of the new method and a pair of <GetCodeReference> tags
         that specify the code in which the method is defined.

         For example, the Mode property of directories (System.IO.DirectoryInfo
         objects) is a code property defined in the Windows PowerShell
         FileSystem provider.

             <Type>
                 <Name>System.IO.DirectoryInfo</Name>
                 <Members>
                     <CodeProperty>
                        <Name>Mode</Name>
                        <GetCodeReference>
                         <TypeName>Microsoft.PowerShell.Commands.FileSystemProvider</TypeName>
                         <MethodName>Mode</MethodName>
                        </GetCodeReference>
                     </CodeProperty>
                 </Members>
             </Type>

     <CodeProperty>: References a static method of a .NET Framework class.

         The <CodeProperty> tag must have a pair of <Name> tags that specify
         the name of the new property and a pair of <GetCodeReference> tags
         that specify the code in which the property is defined.

         For example, the Mode property of directories (System.IO.DirectoryInfo
         objects) is a code property defined in the Windows PowerShell
         FileSystem provider.

             <Type>
                 <Name>System.IO.DirectoryInfo</Name>
                 <Members>
                     <CodeProperty>
                        <Name>Mode</Name>
                        <GetCodeReference>
                         <TypeName>Microsoft.PowerShell.Commands.FileSystemProvider</TypeName>
                         <MethodName>Mode</MethodName>
                        </GetCodeReference>
                     </CodeProperty>
                 </Members>
             </Type>

     <MemberSet>: Defines a collection of members (properties and methods).

         The <MemberSet> tags appear within the primary <Members> tags. The
         tags must enclose a pair of <Name> tags surrounding the name of the
         member set and a pair of secondary <Members> tags that surround the
         members (properties and methods) in the set. Any of the tags that
         create a property (such as <NoteProperty> or <ScriptProperty>) or a
         method (such as <Method> or <ScriptMethod>) can be members of the set.

         In Types.ps1xml files, the <MemberSet> tag is used to define the
         default views of the .NET Framework objects in Windows PowerShell. In
         this case, the name of the member set (the value within the <Name>
         tags) is always “PsStandardMembers”, and the names of the properties
         (the value of the <Name> tag) are one of the following:

        – DefaultDisplayProperty: A single property of an object.

            – DefaultDisplayPropertySet: One or more properties of an object.

            – DefaultKeyPropertySet: One or more key properties of an object.
             A key property identifies instances of property values, such as
             the ID number of items in a session history.

         For example, the following XML defines the default display of services
         (System.ServiceProcess.ServiceController objects) that are returned by
         the Get-Service cmdlet. It defines a member set named
         “PsStandardMembers” that consists of a default property set with the
         Status, Name, and DisplayName properties.

             <Type>
                <Name>System.ServiceProcess.ServiceController</Name>
                <Members>
                 <MemberSet>
                     <Name>PSStandardMembers</Name>
                     <Members>
                         <PropertySet>
                             <Name>DefaultDisplayPropertySet</Name>
                             <ReferencedProperties>
                                <Name>Status</Name>
                                <Name>Name</Name>
                                <Name>DisplayName</Name>
                             </ReferencedProperties>
                         </PropertySet>
                     </Members>
                 </MemberSet>
                </Members>
             </Type>

     <Method>: References a native method of the underlying object.

     <Methods>: A collection of the methods of the object.

     <NoteProperty>: Defines a property with a static value.

         The <NoteProperty> tag must have a pair of <Name> tags that specify
         the name of the new property and a pair of <Value> tags that specify
         the value of the property.

         For example, the following XML creates a Status property for
         directories (System.IO.DirectoryInfo objects). The value of the
         Status property is always “Success”.

             <Type>
                 <Name>System.IO.DirectoryInfo</Name>
                 <Members>
                     <NoteProperty>
                        <Name>Status</Name>
                    <Value>Success</Value>
                     </NoteProperty>
                 </Members>
             </Type>

     <ParameterizedProperty>: Properties that take arguments and return a
                             value.

     <Properties>: A collection of the properties of the object.

     <Property>: A property of the base object.

     <PropertySet>: Defines a collection of properties of the object.

         The <PropertySet> tag must have a pair of <Name> tags that specify
         the name of the property set and a pair of <ReferencedProperty> tags
         that specify the properties. The names of the properties are enclosed
         in <Name> tag pairs.

         In Types.ps1xml, <PropertySet> tags are used to define sets of
         properties for the default display of an object. You can identify the
         default displays by the value “PsStandardMembers” in the <Name> tag
         of a <MemberSet> tag.

         For example, the following XML creates a Status property for
         directories (System.IO.DirectoryInfo objects). The value of the Status
         property is always “Success”.

             <Type>
                 <Name>System.ServiceProcess.ServiceController</Name>
                 <Members>
                     <MemberSet>
                         <Name>PSStandardMembers</Name>
                         <Members>
                             <PropertySet>
                                 <Name>DefaultDisplayPropertySet</Name>
                                 <ReferencedProperties>
                                     <Name>Status</Name
                                     <Name>Name</Name>
                                     <Name>DisplayName</Name>
                                 </ReferencedProperties>
                             </PropertySet>
                         <Members>
                     <MemberSet>
                 <Members>
             <Type>

     <ScriptMethod>: Defines a method whose value is the output of a script.

         The <ScriptMethod> tag must have a pair of <Name> tags that specify
         the name of the new method and a pair of <Script> tags that enclose
         the script block that returns the method result.

         For example, the ConvertToDateTime and ConvertFromDateTime methods of
         management objects (System.System.Management.ManagementObject) are
         script methods that use the ToDateTime and ToDmtfDateTime static
         methods of the System.Management.ManagementDateTimeConverter class.

             <Type>
                 <Name>System.Management.ManagementObject</Name>
                 <Members>
                     <ScriptMethod>
                         <Name>ConvertToDateTime</Name>
                         <Script>
                             [System.Management.ManagementDateTimeConverter]::ToDateTime($args[0])
                         </Script>
                     </ScriptMethod>
                     <ScriptMethod>
                         <Name>ConvertFromDateTime</Name>
                         <Script>
                             [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($args[0])
                         </Script>
                     </ScriptMethod>
                 </Members>
             </Type>

     <ScriptProperty>: Defines a property whose value is the output of a
                        script.

         The <ScriptProperty> tag must have a pair of <Name> tags that specify
         the name of the new property and a pair of <GetScriptBlock> tags
         that enclose the script block that returns the property value.

         For example, the VersionInfo property of files (System.IO.FileInfo
         objects) is a script property that results from using the FullName
         property of the GetVersionInfo static method of
         System.Diagnostics.FileVersionInfo objects.

             <Type>
                <Name>System.IO.FileInfo</Name>
                <Members>
                    <ScriptProperty>
                     <Name>VersionInfo</Name>
                     <GetScriptBlock>
                         [System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName)
                     </GetScriptBlock>
                    </ScriptProperty>
                </Members>
             </Type>

     For more information, see the Windows PowerShell Software Development
     Kit (SDK) in the MSDN (Microsoft Developer Network )library
     at http://go.microsoft.com/fwlink/?LinkId=144538.

Update-TypeData

     To load your Types.ps1xml files into a Windows PowerShell console, use
     the Update-TypeData cmdlet. If you want the types in your file to take
     precedence over types in the built-in Types.ps1xml file, use the
     PrependData parameter of Update-TypeData. Update-TypeData affects only
     the current console. To make the change to all future consoles, export
     the console, or add the Update-TypeData command to your Windows
     PowerShell profile.

Signing a Types.ps1xml File

     To protect users of your Types.ps1xml file, you can sign the file using
     a digital signature. For more information, see about_Signing.

SEE ALSO
    about_Signing
    Copy-Item
    Get-Member
    Update-TypeData

about_try_catch_finally

TOPIC
    about_try_catch_finally

SHORT DESCRIPTION
    Describes how to use the Try, Catch, and Finally blocks to handle
    terminating errors.

LONG DESCRIPTION
    Use Try, Catch, and Finally blocks to respond to or handle terminating
    errors in scripts. The Trap statement can also be used to handle
    terminating errors in scripts. For more information, see about_trap.

    A terminating error stops a statement from running. If Windows PowerShell
    does not handle a terminating error in some way, Windows PowerShell also
    stops running the Function or script using the current pipeline. In other
    languages, such as C#, terminating errors are referred to as exceptions.
    For more information about errors, see about_Errors.

    Use the Try block to define a section of a script in which you want Windows
    PowerShell to monitor for errors. When an error occurs within the Try
    block, the error is first saved to the $Error automatic Variable. Windows
    PowerShell then searches for a Catch block to handle the error. If the Try
    statement does not have a matching Catch block, Windows PowerShell
    continues to search for an appropriate Catch block or Trap statement in the
    parent scopes. After a Catch block is completed or if no appropriate Catch
    block or Trap statement is found, the Finally block is run. If the error
    cannot be handled, the error is written to the error stream.

    A Catch block can include commands for tracking the failure or for
    recovering the expected flow of the script. A Catch block can specify which
    error types it catches. A Try statement can include multiple Catch blocks
    for different kinds of errors.

    A Finally block can be used to free any resources that are no longer needed
    by your script.

    Try, Catch, and Finally resemble the Try, Catch, and Finally keywords used
    in the C# programming language.

Syntax
     A Try statement contains a Try block, zero or more Catch blocks, and zero
     or one Finally block. A Try statement must have at least one Catch block
     or one Finally block.

     The following shows the Try block syntax:

         try {<statement list>}

     The Try keyword is followed by a statement list in braces. If a
     terminating error occurs while the statements in the statement list are
     being run, the script passes the error object from the Try block to an
     appropriate Catch block.

     The following shows the Catch block syntax:

         catch [[<error type>][‘,’ <error type>]*] {<statement list>}

     Error types appear in brackets. The outermost brackets indicate the
     element is optional.

     The Catch keyword is followed by an optional list of error type
     specifications and a statement list. If a terminating error occurs in the
     Try block, Windows PowerShell searches for an appropriate Catch block. If
     one is found, the statements in the Catch block are executed.

     The Catch block can specify one or more error types. An error type is a
     Microsoft .NET Framework exception or an exception that is derived from a
     .NET Framework exception. A Catch block handles errors of the specified
     .NET Framework exception class or of any class that derives from the
     specified class.

     If a Catch block specifies an error type, that Catch block handles that
     type of error. If a Catch block does not specify an error type, that
     Catch block handles any error encountered in the Try block. A Try
     statement can include multiple Catch blocks for the different specified
     error types.

     The following shows the Finally block syntax:

         finally {<statement list>}

     The Finally keyword is followed by a statement list that runs every time
     the script is run, even if the Try statement ran without error or an
     error was caught in a Catch statement.

     Note that pressing CTRL+C stops the pipeline. Objects that are sent to
     the pipeline will not be displayed as output. Therefore, if you include
     a statement to be displayed, such as “Finally block has run”, it will not
     be displayed after you press CTRL+C, even if the Finally block ran.

Catching Errors
     The following sample script shows a Try block with a Catch block:

         try { NonsenseString }
         catch { “An error occurred.” }

     The Catch keyword must immediately follow the Try block or another Catch
     block.

     Windows PowerShell does not recognize “NonsenseString” as a cmdlet or
     other item. Running this script returns the following result:

         An error occurred.

     When the script encounters “NonsenseString”, it causes a terminating
     error. The Catch block handles the error by running the statement list
     inside the block.

Using Multiple Catch Statements
     A Try statement can have any number of Catch blocks. For example, the
     following script has a Try block that downloads MyFile.doc, and it
     contains two Catch blocks:

         try
         {
             $wc = New-Object System.Net.WebClient
             $wc.DownloadFile(“http://www.contoso.com/MyDoc.doc”)
         }
         catch [System.Net.WebException],[System.IO.IOException]
         {
             “Unable to download MyDoc.doc from http://www.contoso.com.”
         }
         catch
         {
             “An error occurred that could not be resolved.”
         }

     The first Catch block handles errors of the System.Net.WebException and
     System.IO.IOException types. The second Catch block does not specify an
     error type. The second Catch block handles any other terminating errors
     that occur.

     Windows PowerShell matches error types by inheritance. A Catch block
     handles errors of the specified .NET Framework exception class or of any
     class that derives from the specified class. The following example
     contains a Catch block that catches a “Command Not Found” error:

         catch [System.Management.Automation.CommandNotFoundException]
             {“Inherited Exception” }

     The specified error type, CommandNotFoundException, inherits from the
     System.SystemException type. The following example also catches a Command
     Not Found error:

         catch [System.SystemException] {“Base Exception” }

     This Catch block handles the “Command Not Found” error and other errors
     that inherit from the SystemException type.

     If you specify an error class and one of its derived classes, place the
     Catch block for the derived class before the Catch block for the general
     class.

Freeing Resources by Using Finally
     To free resources used by a script, add a Finally block after the Try and
     Catch blocks. The Finally block statements run regardless of whether the
     Try block encounters a terminating error. Windows PowerShell runs the
     Finally block before the script terminates or before the current block
     goes out of scope.

     A Finally block runs even if you use CTRL+C to stop the script. A Finally
     block also runs if an Exit keyword stops the script from within a Catch
     block.

SEE ALSO
    about_Errors
    about_trap

about_trap

TOPIC
    about_trap

SHORT DESCRIPTION
    Describes a keyword that handles a terminating error.

LONG DESCRIPTION
    A terminating error stops a statement from running. If Windows PowerShell
    does not handle a terminating error in some way, Windows PowerShell also
    stops running the Function or script in the current pipeline. In other
    languages, such as C#, terminating errors are referred to as exceptions.

    The Trap keyword specifies a list of statements to run when a terminating
    error occurs. Trap statements handle the terminating errors and allow
    execution of the script or Function to continue instead of stopping.

Syntax

     The Trap statement has the following syntax:

         trap [[<error type>]] {<statement list>}

     The Trap statement includes a list of statements to run when a
     terminating error occurs. The Trap keyword can optionally specify an
     error type. An error type requires brackets.

     A script or command can have multiple Trap statements. Trap statements
     can appear anywhere in the script or command.

Trapping All Terminating Errors

     When a terminating error occurs that is not handled in another way in a
     script or command, Windows PowerShell checks for a Trap statement that
     handles the error. If a Trap statement is present, Windows PowerShell
     continues running the script or command in the Trap statement.

     The following example is a very simple Trap statement:

         trap {“Error found.”}

     This Trap statement traps any terminating error. The following example is
     a Function that contains this Trap statement:

         Function TrapTest {
             trap {“Error found.”}
             nonsenseString
             }

     This Function includes a nonsense string that causes an error. Running
     this Function returns the following:

         C:\PS> TrapTest
         Error found.

     The following example includes a Trap statement that displays the error
     by using the $_ automatic Variable:

         Function TrapTest {
             trap {“Error found: $_”}
             nonsenseString
             }

     Running this version of the Function returns the following:

         C:\PS> TrapTest
         Error found: The term ‘nonsenseString’ is not recognized as the name
         of a cmdlet, Function, script file, or operable program. Check the
         spelling of the name, or if a path was included verify that the path
         is correct, and then try again.

     Trap statements can also be more complex. A Trap statement can include
     multiple conditions or Function calls. It can log, test, or even run
     another program.

Trapping Specified Terminating Errors

     The following example is a Trap statement that traps the
     CommandNotFoundException error type:

         trap [System.Management.Automation.CommandNotFoundException]
             {“Command error trapped”}

     When a Function or script encounters a string that does not match a known
     command, this Trap statement displays the “Command error trapped” string.
     After running any statements in the Trap statement list, Windows
     PowerShell writes the error object to the error stream and then continues
     the script.

     Windows PowerShell uses the Microsoft .NET Framework exception types. The
     following example specifies the System.Exception error type:

         trap [System.Exception] {“An error trapped”}

     The CommandNotFoundException error type inherits from the
     System.Exception type. This statement traps an error that is created by
     an unknown command. It also traps other error types.

     You can have more than one Trap statement in a script. Each error can be
     trapped by only one Trap statement. If an error occurs, and more than one
     Trap statement is available, Windows PowerShell uses the Trap statement
     with the most specific error type that matches the error.

     The following script example contains an error. The script includes a
     general Trap statement that traps any terminating error and a specific
     Trap statement that specifies the CommandNotFoundException type.

         trap {“Other terminating error trapped” }
         trap [System.Management.Automation.CommandNotFoundException] {“Command error trapped”}
         nonsenseString

     Running this script produces the following result:

         Command error trapped
         The term ‘nonsenseString’ is not recognized as the name of a cmdlet,
         Function, script file, or operable program. Check the spelling of
         the name, or if a path was included verify that the path is correct,
         and then try again.
         At C:\PS>testScript1.ps1:3 char:19
         +     nonsenseString <<<<

     Because Windows PowerShell does not recognize “nonsenseString” as a
     cmdlet or other item, it returns a CommandNotFoundException error. This
     terminating error is trapped by the specific Trap statement.

     The following script example contains the same Trap statements with a
     different error:

         trap {“Other terminating error trapped” }
         trap [System.Management.Automation.CommandNotFoundException]
             {“Command error trapped”}
         1/$null

     Running this script produces the following result:

         Other terminating error trapped
         Attempted to divide by zero.
         At C:PS> errorX.ps1:3 char:7
         +     1/ <<<< $null

     The attempt to divide by zero does not create a CommandNotFoundException
     error. Instead, that error is trapped by the other Trap statement, which
     traps any terminating error.

Trapping Errors and Scope

     If a terminating error occurs in the same scope as the Trap statement,
     after running the Trap statements, Windows PowerShell continues at the
     statement after the error. If the Trap statement is in a different scope
     from the error, execution continues at the next statement that is in the
     same scope as the Trap statement.

     For instance, if an error occurs in a Function, and the Trap statement is
     in the Function, the script continues at the next statement. For example,
     the following script contains an error and a Trap statement:

         Function Function1 {
             trap { “An error: ” }
             NonsenseString
             “function1 was completed”
             }

     Later in the script, running the Function1 Function produces the
     following result:

         Function1
         An error:
         The term ‘NonsenseString’ is not recognized as the name of a cmdlet,
         Function, script file, or operable program. Check the spelling of the
         name, or if a path was included verify that the path is correct, and
         then try again.
         At C:\PS>TestScript1.ps1:3 char:19
         +     NonsenseString <<<<

         Function1 was completed

     The Trap statement in the Function traps the error. After displaying the
     message, Windows PowerShell resumes running the Function. Note that
     Function1 was completed.

     Compare this with the following example, which has the same error and
     Trap statement. In this example, the Trap statement occurs outside the
     Function:

         Function Function2 {
             NonsenseString
             “function2 was completed”
             }

         trap { “An error: ” }
             . . .
         Function2

     Later in the script, running the Function2 Function produces the
     following result:

         An error:
         The term ‘NonsenseString’ is not recognized as the name of a cmdlet,
         Function, script file, or operable program. Check the spelling of the
         name, or if a path was included verify that the path is correct, and
         then try again.
         At C:\PS>TestScript2.ps1:4 char:19
         +     NonsenseString <<<<

     In this example, the “function2 was completed” command was not run.
     Although both terminating errors occur within a Function, if the Trap
     statement is outside the Function, Windows PowerShell does not go back
     into the Function after the Trap statement runs.

Using the Break and Continue Keywords

     You can use the Break and Continue keywords in a Trap statement to
     determine whether a script or command continues to run after a
     terminating error.

     If you include a Break statement in a Trap statement list, Windows
     PowerShell stops the Function or script. The following sample Function
     uses the Break keyword in a Trap statement:

         C:\PS> Function break_example {
             trap {“Error trapped”; break;}
             1/$null
             “Function completed.”
             }

         C:\PS> break_example
         Error trapped
         Attempted to divide by zero.
         At line:4 char:7

     Because the Trap statement included the Break keyword, the Function does
     not continue to run, and the “Function completed” line is not run.

     If you include a Continue statement in a Trap statement, Windows
     PowerShell resumes after the statement that caused the error, just as it
     would without Break or Continue. With the Continue keyword, however,
     Windows PowerShell does not write an error to the error stream.

     The following sample Function uses the Continue keyword in a Trap
     statement:

         C:\PS> Function continue_example {
             trap {“Error trapped”; continue;}
             1/$null
             “Function completed.”}

         C:\PS> continue_example
         Error trapped
         Function completed.

     The Function resumes after the error is trapped, and the “Function
     completed” statement runs. No error is written to the error stream.

SEE ALSO
    about_Break
    about_Continue
    about_Throw
    about_try_catch_finally
    about_scopes
    about_try_catch_finally