Category Archives: HelpFile

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

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_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_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_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_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_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_script_blocks

TOPIC
    about_script_blocks

SHORT DESCRIPTION
    Defines what a script block is and explains how to use script blocks in
    the Windows PowerShell programming language.

LONG DESCRIPTION
    In the Windows PowerShell programming language, a script block is a
    collection of statements or expressions that can be used as a single unit.
    A script block can accept arguments and return values.

    Syntactically, a script block is a statement list in braces, as shown in
    the following syntax:

        {<statement list>}

    A script block returns the output of all the commands in the script block,
    either as a single object or as an array.

    Like Functions, a script block can include parameters. Use the Param
    keyword to assign named parameters, as shown in the following syntax:

        {
            param ([type]$parameter1 [,[type]$parameter2])
            <statement list>
        }

    In a script block, unlike a Function, you cannot specify parameters outside
    the braces.

    Like Functions, script blocks can include the DynamicParam, Begin, Process,
    and End keywords. For more information, see about_functions and
    about_functions_advanced.

Using Script Blocks

     A script block is an instance of a Microsoft .NET Framework type
     (System.Management.Automation.ScriptBlock). Commands can have script
     block parameter values. For example, the Invoke-Command cmdlet has a
     ScriptBlock parameter that takes a script block value, as shown in this
     example:

         C:\PS> Invoke-Command -scriptblock { Get-Process }
         Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
         ——- ——    —–     —– —– ——     — ———–
             999     28    39100     45020 262    15.88 1844 communicator
             721     28    32696     36536 222    20.84 4028 explorer
         . . .

     The script block that is used as a value can be more complicated, as
     shown in the following example:

         C:\PS> Invoke-Command -scriptblock { param ($uu = “Parameter”);
             “$uu assigned.” }
         Parameter assigned.

     The script block in the preceding example uses the Param keyword to
     create a parameter that has a default value. The following example uses
     the Args parameter of the Invoke-Command cmdlet to assign a different
     value to the parameter:

         C:\PS> Invoke-Command -scriptblock {param ($uu = “Parameter”);
             “$uu assigned.”} -args “Other value”
         Other value assigned.

     You can assign a script block to a Variable, as shown in the following
     example:

         C:\PS> $a = {param ($uu = “Parameter”); “$uu assigned.”}

     You can use the Variable with a cmdlet such as Invoke-Command, as shown
     in the following example:

         C:\PS> Invoke-Command -scriptblock $a -args “Other value”
         Other value assigned.

     You can run a script block that is assigned to a Variable by using the
     call operator (&), as shown in the following example:

         C:\PS> &$a
         Parameter assigned.

     You can also provide a parameter to the script block, as shown in the
     following example:

         C:\PS> &$a “Other value”
         Other value assigned.

     If you want to assign the value that is created by a script block to a
     Variable, use the call operator to run the script block directly, as
     shown in the following example:

         C:\PS> $a = &{param ($uu = “Parameter”); “$uu assigned.”}
         C:\PS> $a
         Parameter assigned.

     For more information about the call operator, see about_operators.

SEE ALSO
    about_functions
    about_functions_advanced
    about_operators

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_script_internationalization

TOPIC
    about_script_internationalization

SHORT DESCRIPTION
    Describes the script internationalization features of Windows PowerShell 2.0
    that make it easy for scripts to display messages and instructions to users
    in their user interface (UI) language.

LONG DESCRIPTION
    The Windows PowerShell script internationalization features allow you to
    better serve users throughout the world by displaying Help and user
    messages for scripts and Functions in the user’s UI language.

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

    The Windows PowerShell 2.0 features used in script internationalization
    are not supported by Windows PowerShell 1.0. Scripts that include these
    features will not run in Windows PowerShell 1.0 without modification.

    To support international Help text, Windows PowerShell 2.0 includes the
    following features:

     — A Data section that separates text strings from code instructions. For
         more information about the Data section, see about_data_sections.

     — New automatic Variables, $PSCulture and $PSUICulture. $PSCulture stores
         the name of the UI language used on the system for elements such as
         the date, time, and currency. The $PSUICulture Variable stores the
         name of the UI language used on the system for user interface elements
         such as menus and text strings.

     — A cmdlet, ConvertFrom-StringData, that converts text strings into
         dictionary-like hash tables to facilitate translation. For more
         information, see ConvertFrom-StringData.

     — A new file type, .psd1, that stores translated text strings. The .psd1
         files are stored in language-specific subdirectories of the script
         directory.

     — A cmdlet, Import-LocalizedData, that imports translated text strings
         for a specified language into a script at runtime. This cmdlet recognizes
         and imports strings in any Windows-supported language. For more
         information see Import-LocalizedData.

THE DATA SECTION: Storing Default Strings

     Use a Data section in the script to store the text strings in the default language.
     Arrange the strings in key/value pairs in a here-string. Each key/value pair must
     be on a separate line. If you include comments, the comments must be on separate
     lines.

     The ConvertFrom-StringData cmdlet converts the key/value pairs in the here-string
     into a dictionary-like hash table that is stored in the value of the Data section
     Variable.

     In the following example, the Data section of the World.ps1 script includes
     the English-United States (en-US) set of prompt messages for a script. The
     ConvertFrom-StringData cmdlet converts the strings into a hash table and stores
     them in the $msgtable Variable.

    $msgTable = Data {
        # culture=”en-US”
        ConvertFrom-StringData @’
        helloWorld = Hello, World.
            errorMsg1 = You cannot leave the user name field blank.
             promptMsg = Please enter your user name.
    ‘@
    }

     For more information about here-strings, see about_Quoting_Rules.

PSD1 FILES: Storing Translated Strings

    Save the script messages for each UI language in separate text files with
    the same name as the script and the .psd1 file name extension. Store the files
    in subdirectories of the script directory with names of cultures in the following
    format:

    <language>–<region>

    Examples: de-DE, ar-SA, and zh-Hans

    For example, if the World.ps1 script is stored in the C:\Scripts directory, you
    would create a file directory structure that resembles the following:

    C:\Scripts
    C:\Scripts\World.ps1
        C:\Scripts\de-DE\World.psd1
            C:\Scripts\ar-SA\World.psd1
            C:\Scripts\zh-CN\World.psd1
        …

    The World.psd1 file in the de-DE subdirectory of the script directory
    might include the following statement:

        ConvertFrom-StringData @’
        helloWorld = Hello, World (in German).
        errorMsg1 = You cannot leave the user name field blank (in German).
            promptMsg = Please enter your user name (in German).
    ‘@

    Similarly, the World.psd1 file in the ar-SA subdirectory of the script directory
    might includes the following statement:

        ConvertFrom-StringData @’
        helloWorld = Hello, World (in Arabic).
        errorMsg1 = You cannot leave the user name field blank (in Arabic).
            promptMsg = Please enter your user name (in Arabic).
    ‘@

Import-LocalizedData: Dynamic Retrieval of Translated Strings

    To retrieve the strings in the UI language of the current user, use
    the Import-LocalizedData cmdlet.

    Import-LocalizedData finds the value of the $PSUICulture automatic
    Variable and imports the content of the <script-name>.psd1 files in
    the subdirectory that matches the $PSUICulture value. Then, it saves
    the imported content in the Variable specified by the value of the
    BindingVariable parameter.

    Import-LocalizedData -bindingVariable msgTable

    For example, if the Import-LocalizedData command appears in the
    C:\Scripts\World.ps1 script and the value of $PSUICulture is
    “ar-SA”, Import-LocalizedData finds the following file:

         C:\Scripts\ar-SA\World.psd1

    Then, it imports the Arabic text strings from the file into
    the $msgTable Variable, replacing any default strings that might
    be defined in the Data section of the World.ps1 script.

    As a result, when the script uses the $msgTable Variable
    to display user messages, the messages are displayed in
    Arabic.

    For example, the following script displays the “Please enter your user
    name” message in Arabic:

    if (!($username)) { $msgTable.promptMsg }

    If Import-LocalizedData cannot find a .psd1 file that matches the
    value of $PSUIculture, the value of $msgTable is not replaced,
    and the call to $msgTable.promptMsg displays the fallback en-US
    strings.

ExAMPLE

    This example shows how the script internationalization features
    are used in a script to display a day of the week to users
    in the language that is set on the computer.

    The following is a complete listing of the Sample1.ps1 script
    file.

    The script begins with a Data section named Day ($Day) that
    contains a ConvertFrom-StringData command. The expression
    submitted to ConvertFrom-StringData is a here-string that
    contains the day names in the default UI culture, en-US, in
    key/value pairs. The ConvertFrom-StringData cmdlet converts
    the key/value pairs in the here-string into a hash table and
    then saves it in the value of the $Day Variable.

    The Import-LocalizedData command imports the contents of the
    .psd1 file in the directory that matches the value of the
    $PSUICulture automatic Variable and then saves it in the $Day
    Variable, replacing the values of $Day that are defined in the
    Data section.

    The remaining commands load the strings into an array and display
    them.

        $Day = DATA {
    # culture=”en-US”
    ConvertFrom-StringData @’
        messageDate = Today is
        d1 = Monday
        d2 = Tuesday
        d3 = Wednesday
        d4 = Thursday
        d5 = Friday
        d6 = Saturday
        d7 = Sunday
        ‘@
    }

    Import-LocalizedData -BindingVariable Day

    # Build an array of weekdays.
    $a = $Day.d1, $Day.d2, $Day.d3, $Day.d4, $Day.d5, $Day.d6, $Day.d7

        # Get the day of the week as a number (Monday = 1).
        # Index into $a to get the name of the day.
        # Use string formatting to build a sentence.

        “{0} {1}” –f $Day.messageDate, $a[(Get-Date -uformat %u)] | Out-Host

    The .psd1 files that support the script are saved in subdirectories of
    the script directory with names that match the $PSUICulture values.

    The following is a complete listing of .\de-DE\sample1.psd1:

        # culture=”en-US”
    ConvertFrom-StringData @’
        messageDate = Today is
        d1 = Monday (in German)
        d2 = Tuesday (in German)
        d3 = Wednesday (in German)
        d4 = Thursday (in German)
            d5 = Friday (in German)
            d6 = Saturday (in German)
            d7 = Sunday (in German)
        ‘@

    As a result, when you run Sample.ps1 on a system on which the value
    of $PSUICulture is de-DE, the output of the script is:

    Today is Friday (in German)

SEE ALSO
    about_data_sections
    about_Automatic_Variables
    about_hash_tables
    about_Quoting_Rules
    ConvertFrom-StringData
    Import-LocalizedData