Category Archives: HelpFile

about_scripts

TOPIC
    about_scripts

SHORT DESCRIPTION
    Describes how to write and run scripts in Windows PowerShell.

LONG DESCRIPTION
    A script is a plain text file that contains one or more Windows PowerShell
    commands. Windows PowerShell scripts have a .ps1 file name extension.

    Writing a script saves a command for later use and makes it easy to share
    with others. Most importantly, it lets you run the commands simply by typing
    the script path and the file name. Scripts can be as simple as a single
    command in a file or as extensive as a complex program.

    Scripts have additional features, such as the #Requires special comment,
    the use of parameters, support for data sections, and digital signing for
    security. You can also write Help topics for scripts and for any Functions
    in the script.

HOW TO WRITE A SCRIPT

    A script can contain any valid Windows PowerShell commands, including single
    commands, commands that use the pipeline, Functions, and control structures
    such as If statements and For loops.

    To write a script, start a text editor (such as Notepad) or a script editor
    (such as the Windows PowerShell Integrated Scripting Environment [ISE]). Type
    the commands and save them in a file with a valid file name and the .ps1 file
    name extension.

    The following example is a simple script that gets the services that are
    running on the current system and saves them to a log file. The log file name
    is created from the current date.

        $date = (Get-Date).dayofyear
        Get-Service | Out-File “$date.log”

    To create this script, open a text editor or a script editor, type these
    commands, and then save them in a file named ServiceLog.ps1.

HOW TO RUN A SCRIPT

    Before you can run a script, you need to change the default Windows
    PowerShell execution policy. The default execution policy, “Restricted”,
    prevents all scripts from running, including scripts that you write on the
    local computer. For more information, see about_execution_policies.

    To run a script, type the full name and the full path to the script file.

    For example, to run the ServicesLog script in the C:\Scripts directory, type:

        c:\scripts\ServicesLog.ps1

    To run a script in the current directory, type the path to the current
    directory, or use a dot to represent the current directory, followed by
    a path backslash (.\).

    For example, to run the ServicesLog.ps1 script in the local directory, type:

        .\ServicesLog.ps1

    As a security feature, Windows PowerShell does not run scripts when you
    double-click the script icon in Windows Explorer or when you type the
    script name without a full path, even when the script is in the current
    directory. For more information about running commands and scripts in
    Windows PowerShell, see about_command_precedence.

RUNNING SCRIPTS REMOTELY

    To run a script on a remote computer, use the FilePath parameter of the
    Invoke-Command cmdlet.

    Enter the path and file name of the script as the value of the FilePath
    parameter. The script must reside on the local computer or in a directory
    that the local computer can access.

    The following command runs the ServicesLog.ps1 script on the Server01 remote
    computer.

        Invoke-Command -computername Server01 -filepath C:\scripts\servicesLog.ps1

PARAMETERS IN SCRIPTS

    To define parameters in a script, use a Param statement. The Param statement
    must be the first statement in a script, except for comments and any
    #Requires statements.

    Script parameters work like Function parameters. The parameter values are
    available to all of the commands in the script. All of the features of
    Function parameters, including the Parameter attribute and its named
    arguments, are also valid in scripts.

    When running the script, script users type the parameters after the script
    name.

    The following example shows a Test-Remote.ps1 script that has a ComputerName
    parameter. Both of the script Functions can access the ComputerName
    parameter value.

        param ($ComputerName = $(throw “ComputerName parameter is required.”))

        Function CanPing {
         $error.clear()
         $tmp = Test-Connection $computername -ErrorAction SilentlyContinue

         if (!$?)
             {Write-Host “Ping failed: $ComputerName.”; return $false}
         else
             {Write-Host “Ping succeeded: $ComputerName”; return $true}
        }

        Function CanRemote {
            $s = New-PSSession $computername -ErrorAction SilentlyContinue

            if ($s -is [System.Management.Automation.Runspaces.PSSession])
                {Write-Host “Remote test succeeded: $ComputerName.”}
            else
                {Write-Host “Remote test failed: $ComputerName.”}
        }

        if (CanPing $computername) {CanRemote $computername}

    To run this script, type the parameter name after the script name.
    For example:

    C:\PS> .\test-remote.ps1 -computername Server01

    Ping succeeded: Server01
    Remote test failed: Server01

    For more information about the Param statement and the Function parameters,
    see about_functions and about_functions_advanced_parameters.

HELP FOR SCRIPTS

    The Get-Help cmdlet gets Help for scripts as well as for cmdlets,
    providers, and Functions. To get Help for a script, type Get-Help and the
    path and file name of the script. If the script path is in your Path
    Environment Variable, you can omit the path.

    For example, to get Help for the ServicesLog.ps1 script, type:

        Get-Help C:\admin\scripts\ServicesLog.ps1

    You can write Help for a script by using either of the two following methods:

    — Comment-Based Help for Scripts

        Create a Help topic by using special keywords in the comments. To create
        comment-based Help for a script, the comments must be placed at the
        beginning or end of the script file. For more information about
        comment-based Help, see about_Comment_Based_Help.

    — XML-Based Help for Scripts

        Create an XML-based Help topic, such as the type that is typically
        created for cmdlets. XML-based Help is required if you are translating
        Help topics into multiple languages.

        To associate the script with the XML-based Help topic, use the
        .ExternalHelp Help comment keyword. For more information about the
        ExternalHelp keyword, see about_Comment_Based_Help. For more information
        about XML-based help, see “How to Write Cmdlet Help” in the MSDN
        (Microsoft Developer Network) library at
        http://go.microsoft.com/fwlink/?LinkID=123415.

SCRIPT SCOPE AND DOT SOURCING

    Each script runs in its own scope. The Functions, Variables, Aliases, and
    drives that are created in the script exist only in the script scope. You
    cannot access these items or their values in the scope in which the
    script runs.

    To run a script in a different scope, you can specify a scope, such as
    Global or Local, or you can dot source the script.

    The dot sourcing feature lets you run a script in the current scope instead
    of in the script scope. When you run a script that is dot sourced, the
    commands in the script run as though you had typed them at the command
    prompt. The Functions, Variables, Aliases, and drives that the script
    creates are created in the scope in which you are working. After the script
    runs, you can use the created items and access their values in your session.

    To dot source a script, type a dot (.) and a space before the script path.

    For example:

        . C:\scripts\UtilityFunctions.ps1

    -or-

        . .\UtilityFunctions.ps1

    After the UtilityFunctions script runs, the Functions and Variables that the
    script creates are added to the current scope.

    For example, the UtilityFunctions.ps1 script creates the New-Profile
    Function and the $ProfileName Variable.

        #In UtilityFunctions.ps1

        Function New-Profile
        {
            Write-Host “Running New-Profile Function
            $profileName = Split-Path $profile -leaf

            if (Test-Path $profile)
             {Write-Error “There is already a $profileName profile on this computer.”}
            else
         {New-Item -type file -path $profile -force }
        }

    If you run the UtilityFunctions.ps1 script in its own script scope, the
    New-Profile Function and the $ProfileName Variable exist only while the
    script is running. When the script exits, the Function and Variable are
    removed, as shown in the following example.

        C:\PS> .\UtilityFunctions.ps1

        C:\PS> New-Profile
        The term ‘new-profile’ is not recognized as a cmdlet, Function, operable
        program, or script file. Verify the term and try again.
        At line:1 char:12
        + new-profile <<<<
         + CategoryInfo         : ObjectNotFound: (new-profile:String) [],
         + FullyQualifiedErrorId : CommandNotFoundException

        C:\PS> $profileName
        C:\PS>

    When you dot source the script and run it, the script creates the
    New-Profile Function and the $ProfileName Variable in your session in your
    scope. After the script runs, you can use the New-Profile Function in your
    session, as shown in the following example.

        C:\PS> . .\UtilityFunctions.ps1

        C:\PS> New-Profile

            Directory: C:\Users\juneb\Documents\WindowsPowerShell

            Mode    LastWriteTime     Length Name
            —-    ————-     —— —-
            -a— 1/14/2009 3:08 PM     0 Microsoft.PowerShellISE_profile.ps1

        C:\PS> $profileName
        Microsoft.PowerShellISE_profile.ps1

    For more information about scope, see about_scopes.

SCRIPTS IN MODULES

    A module is a set of related Windows PowerShell resources that can be
    distributed as a unit. You can use modules to organize your scripts,
    Functions, and other resources. You can also use modules to distribute your
    code to others, and to get code from trusted sources.

    You can include scripts in your modules, or you can create a script module,
    which is a module that consists entirely or primarily of a script and
    supporting resources. A script module is just a script with a .psm1 file
    name extension.

    For more information about modules, see about_modules.

OTHER SCRIPT FEATURES

    Windows PowerShell has many useful features that you can use in scripts.

    #Requires
        You can use a #Requires statement to prevent a script from running
        without specified modules or snap-ins and a specified version of
        Windows PowerShell. For more information, see about_requires.

    $MyInvocation
        The $MyInvocation automatic Variable contains information about the
        current command, including the current script. You can use this Variable
        and its properties to get information about the script while it is
        running. For example, the $MyInvocation.MyCommand.Path Variable contains
        the path and file name of the script.

    Data sections
        You can use the Data keyword to separate data from logic in scripts.
        Data sections can also make localization easier. For more information,
        see about_data_sections and about_Script_Localization.

    Script Signing
        You can add a digital signature to a script. Depending on the execution
        policy, you can use digital signatures to restrict the running of scripts
        that could include unsafe commands. For more information, see
        about_execution_policies and about_Signing.

SEE ALSO
    about_command_precedence
    about_Comment_Based_Help
    about_execution_policies
    about_functions
    about_modules
    about_profiles
    about_requires
    about_scopes
    about_script_blocks
    about_Signing
    Invoke-Command

about_PSSnapins

TOPIC
    about_PSSnapins

SHORT DESCRIPTION
    Describes Windows PowerShell snap-ins and shows how to use and manage them.

LONG DESCRIPTION
    A Windows PowerShell snap-in is a Microsoft .NET Framework assembly that
    contains Windows PowerShell providers and/or cmdlets. Windows PowerShell
    includes a set of basic snap-ins, but you can extend the power and value
    of Windows PowerShell by adding snap-ins that contain providers and cmdlets
    that you create or get from others.

    When you add a snap-in, the cmdlets and providers that it contains are
    immediately available for use in the current session, but the change
    affects only the current session.

    To add the snap-in to all future sessions, save it in your Windows
    PowerShell profile. You can also use the Export-Console cmdlet to save
    the snap-in names to a console file and then use it in future sessions.
    You can even save multiple console files, each with a different set of
    snap-ins.

BUILT-IN SNAP-INS
    Windows PowerShell includes a set of Windows PowerShell snap-ins that
    contain the built-in providers and cmdlets.

    Microsoft.PowerShell.Core
        Contains providers and cmdlets used to manage the basic features of
        Windows PowerShell. It includes the FileSystem, Registry, Alias,
        Environment, Function, and Variable providers and basic cmdlets like
        Get-Help, Get-Command, and Get-History.

    Microsoft.PowerShell.Host
     Contains cmdlets used by the Windows PowerShell host, such as
     Start-Transcript and Stop-Transcript.

    Microsoft.PowerShell.Management
        Contains cmdlets such as Get-Service and Get-ChildItem that are used to
        manage Windows-based features.

    Microsoft.PowerShell.Security
        Contains cmdlets used to manage Windows PowerShell security, such as
        Get-Acl, Get-AuthenticodeSignature, and ConvertTo-SecureString.

    Microsoft.PowerShell.Utility
        Contains cmdlets used to manipulate objects and data, such as
        Get-Member, Write-Host, and Format-List.

FINDING SNAP-INS
    To get a list of the Windows PowerShell snap-ins on your computer, type:

    Get-PSSnapin

    To get the snap-in for each Windows PowerShell provider, type:

        Get-PSProvider | Format-List name, pssnapin

    To get a list of the cmdlets in a Windows PowerShell snap-in, type:

        Get-Command -module <snap-in_name>

INSTALLING A SNAP-IN
    The built-in snap-ins are registered in the system and added to the
    default session when you start Windows PowerShell. However, you have to
    register snap-ins that you create or obtain from others and then add the
    snap-ins to your session.

REGISTERING A SNAP-IN
    A Windows PowerShell snap-in is a program written in a .NET Framework
    language that is compiled into a .dll file. To use the providers and
    cmdlets in a snap-in, you must first register the snap-in (add it to the
    Registry).

    Most snap-ins include an installation program (an .exe or .msi file)
    that registers the .dll file for you. However, if you receive a snap-in as
    a .dll file, you can register it on your system. For more information, see
    “How to Register Cmdlets, Providers, and Host Applications” in the MSDN
    (Microsoft Developer Network) library at
    http://go.microsoft.com/fwlink/?LinkID=143619.

    To get all the registered snap-ins on your system or to verify that a
    snap-in is registered, type:

    Get-PSSnapin -registered

ADDING THE SNAP-IN TO THE CURRENT SESSION
    To add a registered snap-in to the current session, use the Add-PSSnapin
    cmdlet. For example, to add the Microsoft SQL Server snap-in to the
    session, type:

    Add-PSSnapin sql

    After the command is completed, the providers and cmdlets in the snap-in
    are available in the session. However, they are available only in the
    current session unless you save them.

SAVING THE SNAP-INS
    To use a snap-in in future Windows PowerShell sessions, add the
    Add-PSSnapin command to your Windows PowerShell profile. Or, export
    the snap-in names to a console file.

    If you add the Add-PSSnapin command to your profile, it is available
    in all future Windows PowerShell sessions. If you export the names of
    the snap-ins in your session, you can use the export file only when you
    need the snap-ins.

    To add the Add-PSSnapin command to your Windows PowerShell profile,
    open your profile, paste or type the command, and then save the profile.
    For more information, see about_profiles.

    To save the snap-ins from a session in console file (.psc1), use
    the Export-Console cmdlet. For example, to save the snap-ins in
    the current session configuration to the NewConsole.psc1 file in the
    current directory, type:

    Export-Console NewConsole

    For more information, see Export-Console.

OPENING WINDOWS POWERSHELL WITH A CONSOLE FILE
    To use a console file that includes the snap-in, start Windows PowerShell
    (Powershell.exe) from the command prompt in Cmd.exe or in another
    Windows PowerShell session. Use the PsConsoleFile parameter to specify
    the console file that includes the snap-in. For example, the following
    command starts Windows PowerShell with the NewConsole.psc1 console file:

    powershell.exe -psconsolefile NewConsole.psc1

    The providers and cmdlets in the snapin are now available for use in
    the session.

REMOVING A SNAP-IN
    To remove a Windows PowerShell snap-in from the current session, use the
    Remove-PSSnapin cmdlet. For example, to remove the SQL Server
    snap-in from the current session, type:

    Remove-PSSnapin sql

    This cmdlet removes the snap-in from the session. The snap-in is still
    loaded, but the providers and cmdlets that it supports are no longer
    available.

SEE ALSO
    Add-PSSnapin
    Get-PSSnapin
    Remove-PSSnapin
    Export-Console
    Get-Command
    about_profiles

about_Quoting_Rules

TOPIC
    about_Quoting_Rules

SHORT DESCRIPTION
    Describes rules for using single and double quotation marks
    in Windows PowerShell.

LONG DESCRIPTION
    Quotation marks are used to specify a literal string. You can enclose a
    string in single quotation marks (‘) or double quotation marks (“).

    Quotation marks are also used to create a here-string. A here-string is a
    single-quoted or double-quoted string in which quotation marks are
    interpreted literally. A here-string can span multiple lines. All the
    lines in a here-string are interpreted as strings, even though they are
    not enclosed in quotation marks.

    In commands to remote computers, quotation marks define the parts of
    the command that are run on the remote computer. In a remote session,
    quotation marks also determine whether the Variables in a command are
    interpreted first on the local computer or on the remote computer.

Single and Double-Quoted Strings

     When you enclose a string in double quotation marks (a double-quoted
     string), Variable names that are preceded by a dollar sign ($) are
     replaced with the Variable‘s value before the string is passed to the
     command for processing.

     For example:

         $i = 5
         “The value of $i is $i.”

     The output of this command is:

         The value of 5 is 5.

     Also, in a double-quoted string, expressions are evaluated, and the
     result is inserted in the string. For example:

     “The value of $(2+3) is 5.”

     The output of this command is:

     The value of 5 is 5.

     When you enclose a string in single-quotation marks (a single-quoted
     string), the string is passed to the command exactly as you type it.
     No substitution is performed. For example:

         $i = 5
         ‘The value of $i is $i.’

     The output of this command is:

         The value $i is $i.

     Similarly, expressions in single-quoted strings are not evaluated. They
     are interpreted as literals. For example:

     ‘The value of $(2+3) is 5.’

     The output of this command is:

     The value of $(2+3) is 5.

     To prevent the substitution of a Variable value in a double-quoted
     string, use the backtick character (`)(ASCII 96), which is the
     Windows PowerShell escape character.

     In the following example, the backtick character that precedes the first
     $i Variable prevents Windows PowerShell from replacing the Variable name
     with its value. For example:

         $i = 5
         “The value of `$i is $i.”

     The output of this command is:

         The value $i is 5.

     To make double-quotation marks appear in a string, enclose the entire
     string in single quotation marks. For example:

         ‘As they say, “live and learn.”‘

     The output of this command is:

         As they say, “live and learn.”

     You can also enclose a single-quoted string in a double-quoted string.
     For example:

         “As they say, ‘live and learn.'”

     The output of this command is:

         As they say, ‘live and learn.’

     Or, double the quotation marks around a double-quoted phrase. For
     example:

         “As they say, “”live and learn.”””

     The output of this command is:

         As they say, “live and learn.”

     To include a single quotation mark in a single-quoted string, use a
     second consecutive single quote. For example:

         ‘don”t’

     The output of this command is:

         don’t

     To force Windows PowerShell to interpret a double quotation mark
     literally, use a backtick character. This prevents Windows PowerShell
     from interpreting the quotation mark as a string delimiter. For example:

         “Use a quotation mark (`”) to begin a string.”

     Because the contents of single-quoted strings are
     interpreted literally, you cannot use the backtick character to
     force a literal character interpretation in a single-quoted string.

     For example, the following command generates an error because Windows
     PowerShell does not recognize the escape character. Instead, it
     interprets the second quotation mark as the end of the string.

     PS C:\> ‘Use a quotation mark (`’) to begin a string.’
         Unexpected token ‘)’ in expression or statement.
         At line:1 char:27
         + ‘Use a quotation mark (`’) <<<< to begin a string.’

Single and Double-Quoted Here-Strings

     The quotation rules for here-strings are slightly different.

     A here-string is a single-quoted or double-quoted string in
     which quotation marks are interpreted literally. A here-string can
     span multiple lines. All the lines in a here-string are interpreted
     as strings even though they are not enclosed in quotation marks.

     Like regular strings, Variables are replaced by their values in
     double-quoted here-strings. In single-quoted here-strings, Variables
     are not replaced by their values.

     You can use here-strings for any text, but they are particularly
     useful for the following kinds of text:

         – Text that contains literal quotation marks
         – Multiple lines of text, such as the text in an HTML or XML document
         – The Help text for a script or Function

     A here-string can have either of the following formats, where <Enter>
     represents the linefeed or newline hidden character that is added when
     you press the ENTER key.

     Format 1:

     @”<Enter>
         <string> [string] …<Enter>
         “@

     Format 2:

     @'<Enter>
         <string> [string] …<Enter>
         ‘@

     In either format, the closing quotation mark must be the first character
     in the line.

     A here-string contains all the text between the two hidden characters.
     In the here-string, all quotation marks are interpreted literally.
     For example:

     @”
     For help, type “Get-Help
     “@

     The output of this command is:

     For help, type “Get-Help

     Using a here-string can simplify using a string in a command. For
     example:

     @”
         Use a quotation mark (‘) to begin a string.
         “@

     The output of this command is:

         Use a quotation mark (‘) to begin a string.

     In single-quoted here-strings, Variables are interpreted literally and
     reproduced exactly. For example:

         @’
     The $profile Variable contains the path
         of your Windows PowerShell profile.
         ‘@

     The output of this command is:

     The $profile Variable contains the path
         of your Windows PowerShell profile.

     In double-quoted here-strings, Variables are replaced by their values.
     For example:

     @”
         Even if you have not created a profile,
         the path of the profile file is:
         $profile.
         “@

     The output of this command is:

     Even if you have not created a profile,
     the path of the profile file is:
     C:\Users\User01\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.

     Here-strings are typically used to assign multiple lines to
     a Variable. For example, the following here-string assigns a
     page of XML to the $page Variable.

        $page = [XML] @”
        <command:command xmlns:maml=”http://schemas.microsoft.com/maml/2004/10″
        xmlns:command=”http://schemas.microsoft.com/maml/dev/command/2004/10″
        xmlns:dev=”http://schemas.microsoft.com/maml/dev/2004/10″>
        <command:details>
                <command:name>
                     Format-Table
            </command:name>
            <maml:description>
            <maml:para>Formats the output as a table.</maml:para>
            </maml:description>
            <command:verb>format</command:verb>
            <command:noun>table</command:noun>
            <dev:version></dev:version>
        </command:details>
        …
        </command:command>
        “@

     Here-strings are also a convenient format for input to the
     ConvertFrom-StringData cmdlet, which converts here-strings to hash
     tables. For more information, see ConvertFrom-StringData.

SEE ALSO
    about_escape_characters
    ConvertFrom-StringData

about_Redirection

TOPIC
    about_Redirection

SHORT DESCRIPTION
    Describes how to redirect output from Windows PowerShell to text files.

LONG DESCRIPTION
    By default, Windows PowerShell sends its command output to the Windows
    PowerShell console. However, you can direct the output to a text
    file, and you can redirect error output to the regular output stream.

    You can use the following methods to redirect output:

        – Use the Out-File cmdlet, which sends command output to a text file.
         Typically, you use the Out-File cmdlet when you need to use its
         parameters, such as the Encoding, Force, Width, or NoClobber
         parameters.

        – Use the Tee-Object cmdlet, which sends command output to a text file
         and then sends it to the pipeline.

        – Use the Windows PowerShell redirection operators.

     The Windows PowerShell redirection operators are as follows.

     Operator Description                Example
     ——– ———————-     ——————————
     >         Sends output to the        Get-Process > process.txt
                specified file.

     >>        Appends the output to     dir *.ps1 >> scripts.txt
                the contents of the
                specified file.

     2>        Sends errors to the        Get-Process none 2> errors.txt
                specified file.

     2>>     Appends the errors to     Get-Process none 2>> save-errors.txt
                the contents of the
                specified file.

     2>&1     Sends errors to the        Get-Process none, powershell 2>&1
                success output stream.

    The syntax of the redirection operators is as follows:

     <input> <operator> [<path>\]<file>

    If the specified file already exists, the redirection operators that do not
    append data (> and 2>) overwrite the current contents of the file without
    warning. However, if the file is a read-only, hidden, or system file, the
    redirection fails. The append redirection operators (>> and 2>>) do not
    write to a read-only file, but they append content to a system or hidden
    file.

    To force the redirection of content to a read-only, hidden, or system file,
    use the Out-File cmdlet with its Force parameter. When you are writing to
    files, the redirection operators use Unicode encoding. If the file has a
    different encoding, the output might not be formatted correctly. To
    redirect content to non-Unicode files, use the Out-File cmdlet with its
    Encoding parameter.

SEE ALSO
    Out-File
    Tee-Object
    about_operators
    about_Command_Syntax
    about_Path_Syntax

about_Ref

TOPIC
    about_Ref

SHORT DESCRIPTION
    Describes how to create and use a reference Variable type.

LONG DESCRIPTION
    You can use the reference Variable type to permit a method to change the
    value of a Variable that is passed to it.

    When the [ref] type is associated with an object, it returns a reference
    to that object. If the reference is used with a method, the method can
    refer to the object that was passed to it. If the object is changed within
    the method, the change appears as a change in the value of the Variable
    when control returns to the calling method.

    To use referencing, the parameter must be a reference Variable. If it is
    not, an InvalidArgument exception is thrown.

    The parameters used in method invocations must match the type required
    by the methods.

    Examples:

        PS> Function swap([ref]$a,[ref]$b)
        >> {
        >>     $a.value,$b.value = $b.value,$a.value
        >> }

        PS> $a = 1
        PS> $b = 10
        PS> $a,$b
        1
        10
        PS> swap ([ref]$a) ([ref]$b)
        PS> $a,$b
        10
        1

        PS C:\ps-test> Function double
        >> {
        >>     param ([ref]$x) $x.value = $x.value * 2
        >> }

        PS C:> $number = 8
        PS C:> $number
        8
        PS C> double ([ref]$number)
        PS C> $number
        16

        The Variable must be a reference Variable.

        PS C:\ps-test> double $number
        double : Reference type is expected in argument.
        At line:1 char:7
        + double <<<< $number

SEE ALSO
    about_Variables
    about_environment_variables
    about_functions
    about_script_blocks

about_regular_expressions

TOPIC
    about_regular_expressions

SHORT DESCRIPTION
    Describes regular expressions in Windows PowerShell.

LONG DESCRIPTION
    Windows PowerShell supports the following regular expression characters.

        Format Logic                            Example
        ——– ——————————- ———————–
        value    Matches exact characters         “book” -match “oo”
                 anywhere in the original value.

        .        Matches any single character.    “copy” -match “c..y”

        [value] Matches at least one of the     “big” -match “b[iou]g”
                 characters in the brackets.

        [range] Matches at least one of the     “and” -match “[a-e]nd”
                 characters within the range.
                 The use of a hyphen (–) allows
                 you to specify an adjacent
                 character.

        [^]     Matches any characters except    “and” -match “[^brt]nd”
                 those in brackets.

        ^        Matches the beginning            “book” -match “^bo”
                 characters.

        $        Matches the end characters.     “book” -match “ok$”

        *        Matches any instances            “baggy” -match “g*”
                 of the preceding character.

        ?        Matches one instance             “baggy” -match “g?”
                 of the preceding character.

        \        Matches the character that     “Try$” -match “Try\$”
                 follows as an escaped character.

    Windows PowerShell supports the character classes available in
    Microsoft .NET Framework regular expressions.

        Format Logic                            Example
        ——– ——————————- ———————–
        \p{name} Matches any character in the     “abcd defg” -match “\p{Ll}+”
                 named character class specified
                 by {name}. Supported names are
                 Unicode groups and block
                 ranges such as Ll, Nd,
                 Z, IsGreek, and IsBoxDrawing.

        \P{name} Matches text not included in     1234 -match “\P{Ll}+”
                 the groups and block ranges
                 specified in {name}.

        \w     Matches any word character.     “abcd defg” -match “\w+”
                 Equivalent to the Unicode        (this matches abcd)
                 character categories [\p{Ll}
                 \p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}].
                 If ECMAScript-compliant behavior
                 is specified with the ECMAScript
                 option, \w is equivalent to
                 [a-zA-Z_0-9].

        \W     Matches any nonword character. “abcd defg” -match “\W+”
                 Equivalent to the Unicode        (This matches the space)
                 categories [^\p{Ll}\p{Lu}\p{Lt}
                 \p{Lo}\p{Nd}\p{Pc}].

        \s     Matches any white-space         “abcd defg” -match “\s+”
                 character. Equivalent to the
                 Unicode character categories
                 [\f\n\r\t\v\x85\p{Z}].

        \S     Matches any non-white-space     “abcd defg” -match “\S+”
                 character. Equivalent to the
                 Unicode character categories
                 [^\f\n\r\t\v\x85\p{Z}].

        \d     Matches any decimal digit.     12345 -match “\d+”
                 Equivalent to \p{Nd} for
                 Unicode and [0-9] for non-
                 Unicode behavior.

        \D     Matches any nondigit.            “abcd” -match “\D+”
                 Equivalent to \P{Nd} for
                 Unicode and [^0-9] for non-
                 Unicode behavior.

    Windows PowerShell supports the quantifiers available in .NET Framework
    regular expressions. The following are some examples of quantifiers.

        Format Logic                            Example
        ——– ——————————- ———————–
        *        Specifies zero or more matches; “abc” -match “\w*”
                 for example, \w* or (abc)*.
                 Equivalent to {0,}.

        +        Matches repeating instances of “xyxyxy” -match “xy+”
                 the preceding characters.

        ?        Specifies zero or one matches; “abc” -match “\w?”
                 for example, \w? or (abc)?.
                 Equivalent to {0,1}.

        {n}     Specifies exactly n matches;     “abc” -match “\w{2}”
                 for example, (pizza){2}.

        {n,}     Specifies at least n matches;    “abc” -match “\w{2,}”
                 for example, (abc){2,}.

        {n,m}    Specifies at least n, but no     “abc” -match “\w{2,3}”
                 more than m, matches.

    All the comparisons shown in the preceding table evaluate to true.

    Notice that the escape character for regular expressions, a backslash (\),
    is different from the escape character for Windows PowerShell. The
    escape character for Windows PowerShell is the backtick character (`)
    (ASCII 96).

    For more information, see the “Regular Expression Language Elements” topic
    in the Microsoft Developer Network (MSDN) library
    at http://go.microsoft.com/fwlink/?LinkId=133231.

SEE ALSO
    about_Comparison_Operators
    about_operators

about_remote

TOPIC
    about_remote

SHORT DESCRIPTION
    Describes how to run remote commands in Windows PowerShell.

LONG DESCRIPTION
    You can run remote commands on a single computer or on multiple
    computers by using a temporary or persistent connection. You can also
    start an interactive session with a single remote computer.

    This topic provides a series of examples to show you how to
    run different types of remote command. After you try these basic
    commands, read the Help topics that describe each cmdlet that is
    used in these commands. The topics provide the details and explain
    how you can modify the commands to meet your needs.

    Note: To use Windows PowerShell remoting, the local and remote computers
         must be configured for remoting. For more information, see
         about_remote_requirements.

HOW TO START AN INTERACTIVE SESSION (Enter-PSSession)

     The easiest way to run remote commands is to start an
     interactive session with a remote computer.

     When the session starts, the commands that you type run on the
     remote computer, just as though you typed them directly
     on the remote computer. You can connect to only one
     computer in each interactive session.

     To start an interactive session, use the Enter-PSSession
     cmdlet. The following command starts an interactive session
     with the Server01 computer:

    Enter-PSSession server01

     The command prompt changes to indicate that you are connected
     to the Server01 computer.

    Server01\PS>

     Now, you can type commands on the Server01 computer.

     To end the interactive session, type:

    Exit-PSSession

     For more information, see Enter-PSSession.

HOW TO USE CMDLETS THAT HAVE A COMPUTERNAME PARAMETER TO GET REMOTE DATA

    Several cmdlets have a ComputerName parameter that lets you
    get objects from remote computers.

    Because these cmdlets do not use WS-Management-based Windows PowerShell
    remoting, you can use the ComputerName parameter of these cmdlets on any
    computer that is running Windows PowerShell. The computers do not have to
    be configured for Windows PowerShell remoting, and the computers do not
    have to meet the system requirements for remoting.

    The following cmdlets have a ComputerName parameter:

        Clear-EventLog    Limit-EventLog
        Get-Counter     New-EventLog
        Get-EventLog     Remove-EventLog
        Get-HotFix        Restart-Computer
        Get-Process     Show-EventLog
        Get-Service     Show-Service
        Get-WinEvent     Stop-Computer
        Get-WmiObject     Write-EventLog

    For example, the following command gets the services on
    the Server01 remote computer:

    Get-Service -computername server01

    Typically, cmdlets that support remoting without special configuration
    have a ComputerName parameter and do not have a Session parameter. To
    find these cmdlets in your session, type:

        Get-Command | where { $_.parameters.keys -contains “ComputerName” -and $_.parameters.keys -notcontains “Session”}

HOW TO RUN A REMOTE COMMAND

    To run other commands on remote computers, use the
    Invoke-Command cmdlet.

    To run a single command or a few unrelated commands, use the
    ComputerName parameter of Invoke-Command to specify the remote
    computers. Use the ScriptBlock parameter to specify the command.

    For example, the following command runs a Get-Culture command
    on the Server01 computer.

    Invoke-Command -computername Server01 -scriptblock {Get-Culture}

    The ComputerName parameter is designed for situation in which you run
    a single command or several unrelated commands on one or many computers.
    To establish a persistent connection to a remote computer, use
    the Session parameter.

HOW TO CREATE A PERSISTENT CONNECTION (PSSESSION)

    When you use the ComputerName parameter of the Invoke-Command
    cmdlet, Windows PowerShell establishes a connection just for the
    command. Then, it closes the connection when the command is complete. Any
    Variables or Functions that are defined in the command are lost.

    To create a persistent connection to a remote computer, use the
    New-PSSession cmdlet. For example, the following command creates
    PSSessions on the Server01 and Server02 computers and then saves the
    PSSessions in the $s Variable.

    $s = New-PSSession -computername Server01, Server02

HOW TO RUN COMMANDS IN A PSSESSION

    With a PSSession, you can run a series of remote commands that
    share data, like Functions, Aliases, and the values of Variables.
    To run commands in a PSSession, use the Session parameter of the
    Invoke-Command cmdlet.

    For example, the following command uses the Invoke-Command cmdlet
    to run a Get-Process command in the PSSessions on the Server01
    and Server02 computers. The command saves the processes in a $p
    Variable in each PSSession.

        Invoke-Command -session $s -scriptblock {$p = Get-Process}

    Because the PSSession uses a persistent connection, you can run
    another command in the same PSSession that uses the $p Variable.
    The following command counts the number of processes saved in $p.

        Invoke-Command -session $s -scriptblock {$p.count}

HOW TO RUN A REMOTE COMMAND ON MULTIPLE COMPUTERS

    To run a remote command on multiple computers, type all of
    the computer names in the value of the ComputerName parameter of
    Invoke-Command. Separate the names with commas.

    For example, the following command runs a Get-Culture command
    on three computers:

    Invoke-Command -computername S1, S2, S3 -scriptblock {Get-Culture}

    You can also run a command in multiple PSSessions. The following
    commands create PSSessions on the Server01, Server02, and Server03
    computers and then run a Get-Culture command in each of the PSSessions.

        $s = New-PSSession -computername S1, S2, S3
    Invoke-Command -session $s -scriptblock {Get-Culture}

    To include the local computer list of computers, type the name of
    the local computer, type a dot (.), or type “localhost”.

    Invoke-Command -computername S1, S2, S3, localhost -scriptblock {Get-Culture}

HOW TO RUN A SCRIPT ON REMOTE COMPUTERS

    To run a local script on remote computers, use the
    FilePath parameter of Invoke-Command.

    For example, the following command runs the Sample.ps1 script
    on the S1 and S2 computers:

        Invoke-Command -computername S1, S2 -filepath C:\Test\Sample.ps1

    The results of the script are returned to the local computer. You
    do not need to copy any files.

HOW TO STOP A REMOTE COMMAND

To interrupt a command, press CTRL+C. The interrupt request is
passed to the remote computer where it terminates the remote command.

FOR MORE INFORMATION

    — For information about the system requirements for remoting,
     see about_remote_requirements.

    — For help in formatting remote output, see about_remote_Output.

    — For information about how remoting works, how to manage remote
     data, special configurations, security issues, and other frequently
     asked questions, see about_remote_FAQ.

    — For help in resolving remoting errors, see about_remote_TroubleShooting.

    — For information about PSSessions and persistent connections, see
     about_pssessions.

    — For information about Windows PowerShell background jobs, see
     about_jobs.

KEYWORDS
    about_Remoting

SEE ALSO
    about_pssessions
    about_remote_requirements
    about_remote_FAQ
    about_remote_TroubleShooting
    Enter-PSSession
    Invoke-Command
    New-PSSession

about_remote_FAQ

TOPIC
    about_remote_FAQ

SHORT DESCRIPTION
    Contains questions and answers about running remote commands
    in Windows PowerShell.

LONG DESCRIPTION
When you work remotely, you type commands in Windows PowerShell on one
computer (known as the “local computer”), but the commands run on another
computer (known as the “remote computer”). The experience of working
remotely should be as much like working directly at the remote computer
as possible.

    Note: To use Windows PowerShell remoting, the remote computer
         must be configured for remoting. For more information, see
         about_remote_requirements.

MUST BOTH COMPUTERS HAVE WINDOWS POWERSHELL INSTALLED?

Yes. To work remotely, the local and remote computers must have
Windows PowerShell, the Microsoft .NET Framework 2.0, and the Web
Services for Management (WS-Management) protocol. Any files and
other resources that are needed to execute a particular command
must be on the remote computer.

You must have permission to connect to the remote computer, permission
to run Windows PowerShell, and permission to access data stores (such as
files and folders), and the Registry on the remote computer.

For more information, see about_remote_requirements.

HOW DOES REMOTING WORK?

When you submit a remote command, the command is transmitted across
the network to the Windows PowerShell engine on the remote computer,
and it runs in the Windows PowerShell client on the remote computer.
The command results are sent back to the local computer and appear in
the Windows PowerShell session on the local computer.

To transmit the commands and receive the output, Windows PowerShell uses
the WS-Management protocol. For information about the WS-Management
protocol, see “WS-Management Protocol” in the MSDN (Microsoft Developer
Network) library at http://go.microsoft.com/fwlink/?LinkId=144634.

IS WINDOWS POWERSHELL REMOTING SECURE?

    When you connect to a remote computer, the system uses the user
    name and password credentials on the local computer or the credentials
    that you supply in the command to log you in to the remote computer.
    The credentials and the rest of the transmission are encrypted.

    To add additional protection, you can configure the remote computer
    to use Secure Sockets Layer (SSL) instead of HTTP to listen for
    Windows Remote Management (WinRM) requests. Then, users can use
    the UseSSL parameters of the Invoke-Command, New-PSSession, and
    Enter-PSSession cmdlets when establishing a connection. This option
    uses the more secure HTTPS channel instead of HTTP.

DO ALL REMOTE COMMANDS REQUIRE WINDOWS POWERSHELL REMOTING?

No. Several cmdlets have a ComputerName parameter that lets
you get objects from the remote computer.

These cmdlets do not use Windows PowerShell remoting. So, you
can use them on any computer that is running Windows PowerShell,
even if the computer is not configured for Windows PowerShell
remoting or if the computer does not meet the requirements for
Windows PowerShell remoting.

These cmdlets include the following cmdlets:

     Get-Process
     Get-Service
     Get-WinEvent
     Get-EventLog
     Get-WmiObject
     Test-Connection

To find all the cmdlets with a ComputerName parameter, type:

        Get-Help * -parameter ComputerName

To determine whether the ComputerName parameter of a particular cmdlet
requires Windows PowerShell remoting, see the parameter description. To
display the parameter description, type:

    Get-Help <cmdlet-name> -parameter ComputerName

For example:

        Get-Help Get-Process -parameter Computername

For all other commands, use the Invoke-Command cmdlet.

HOW DO I RUN A COMMAND ON A REMOTE COMPUTER?

To run a command on a remote computer, use the Invoke-Command cmdlet.

Enclose your command in braces ( {} ) to make it a script block. Use
the ScriptBlock parameter of Invoke-Command to specify the command.

You can use the ComputerName parameter of Invoke-Command to specify
a remote computer. Or, you can create a persistent connection to a remote
computer (a session) and then use the Session parameter of Invoke-Command
to run the command in the session.

For example, the following commands run a Get-Process command remotely.

     Invoke-Command -computername Server01, Server02 -scriptblock {Get-Process}

        – OR –

     Invoke-Command -session $s -scriptblock {Get-Process}

To interrupt a remote command, type CTRL+C. The interruption request is
passed to the remote computer, where it terminates the remote command.

For more information about remote commands, see about_remote and the Help
topics for the cmdlets that support remoting.

CAN I JUST “TELNET INTO” A REMOTE COMPUTER?

    You can use the Enter-PSSession cmdlet to start an interactive session
    with a remote computer.

    At the Windows Powershell prompt, type:

    Enter-PSSession <ComputerName>

    The command prompt changes to show that you are connected to the remote
    computer.

        <ComputerName>\C:>

    Now, the commands that you type run on the remote computer just as
    though you typed them directly on the remote computer.

    To end the interactive session, type:

        Exit-PSSession

    An interactive session is a persistent session that uses the WS-Management
    protocol. It is not the same as using Telnet, but it provides a similar
    experience.

    For more information, see Enter-PSSession.

CAN I CREATE A PERSISTENT CONNECTION?

    Yes. You can run remote commands by specifying the name of the
    remote computer, its NetBIOS name, or its IP address. Or, you can run
    remote commands by specifying a Windows PowerShell session (PSSession)
    that is connected to the remote computer.

    When you use the ComputerName parameter of Invoke-Command or
    Enter-PSSession, Windows PowerShell establishes a temporary
    connection. Windows PowerShell uses the connection to run only the current
    command, and then it closes the connection. This is a very efficient
    method for running a single command or several unrelated commands, even
    on many remote computers.

    When you use the New-PSSession cmdlet to create a PSSession, Windows
    PowerShell establishes a persistent connection for the PSSession. Then,
    you can run multiple commands in the PSSession, including commands that
    share data.

    Typically, you create a PSSession to run a series of related commands
    that share data. Otherwise, the temporary connection created by the
    ComputerName parameter is sufficient for most commands.

    For more information about sessions, see about_pssessions.

CAN I RUN COMMANDS ON MORE THAN ONE COMPUTER AT A TIME?

Yes. The ComputerName parameter of the Invoke-Command cmdlet accepts
multiple computer names, and the Session parameter accepts
multiple PSSessions.

When you run an Invoke-Command command, Windows PowerShell runs the
commands on all of the specified computers or in all of the specified
PSSessions.

Windows PowerShell can manage hundreds of concurrent remote connections.
However, the number of remote commands that you can send might be limited
by the resources of your computer and its capacity to establish and
maintain multiple network connections.

For more information, see the example in the Invoke-Command Help
topic.

WHERE ARE MY PROFILES?

    Windows PowerShell profiles are not run automatically in remote sessions,
    so the commands that the profile adds are not present in the session. In
    addition, the $profile automatic Variable is not populated in remote
    sessions.

    To run a profile in a session, use the Invoke-Command cmdlet.

    For example, the following command runs the CurrentUserCurrentHost profile
    from the local computer in the session in $s.

        Invoke-Command -session $s -filepath $profile

    The following command runs the CurrentUserCurrentHost profile from
    the remote computer in the session in $s. Because the $profile Variable
    is not populated, the command uses the explicit path to the profile.

        Invoke-Command -session $s {. “$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1”}

    After running this command, the commands that the profile adds to the session
    are available in $s.

    You can also use a startup script in a session configuration to run a
    profile in every remote session that uses the session configuration.

    For more information about Windows PowerShell profiles,
    see about_profiles. For more information about session configurations,
    see Register-PSSessionConfiguration.

HOW DOES THROTTLING WORK ON REMOTE COMMANDS?

To help you manage the resources on your local computer, Windows
PowerShell includes a per-command throttling feature that lets you
limit the number of concurrent remote connections that are established
for each command.

The default is 32 concurrent connections, but you can use the
ThrottleLimit parameters of the cmdlets to set a custom throttle limit
for particular commands.

When you use the throttling feature, remember that it is applied to each
command, not to the entire session or to the computer. If you are running
commands concurrently in several sessions or PSSessions, the number of
concurrent connections is the sum of the concurrent connections in all
the sessions.

To find cmdlets with a ThrottleLimit parameter, type:

    Get-Help * -parameter ThrottleLimit

ARE THERE SYSTEM-SPECIFIC DIFFERENCES IN REMOTING?

When you run commands on multiple computers, be aware of the differences
between the remote computers, such as differences in the operating systems,
the file system structure, and the Registry.

When you connect to a remote computer that is running Windows Vista or
Windows Server 2003, the default starting location is the home directory
of the current user, which is stored in the %homepath% Environment Variable
($env:homepath) and the Windows PowerShell $home Variable. In Windows Vista,
the home directory is typically C:\Users\<UserName>. In Windows Server 2003,
the home directory is typically C:\Documents and Settings\<UserName>.

When you connect to a remote computer that is running Windows XP, the
default starting location is the home directory of the default user, which is
stored in the %homepath% Environment Variable ($env:homepath) for the default
user. The home directory is typically C:\Documents and Setting\Default User.

IS THE OUTPUT OF REMOTE COMMANDS DIFFERENT FROM LOCAL OUTPUT?

When you use Windows PowerShell locally, you send and receive “live” .NET
Framework objects; “live” objects are objects that are associated with
actual programs or system components. When you invoke the methods or change
the properties of live objects, the changes affect the actual program or
component. And, when the properties of a program or component change,
the properties of the object that represent them also change.

However, because most live objects cannot be transmitted over the network,
Windows PowerShell “serializes” most of the objects sent in remote commands,
that is, it converts each object into a series of XML (Constraint Language
in XML [CLiXML]) data elements for transmission.

When Windows PowerShell receives a serialized object, it converts
the XML into a deserialized object type. The deserialized object
is an accurate record of the properties of the program or component at
a previous time, but it is no longer “live”, that is, it
is no longer directly associated with the component. And, the methods are
removed because they are no longer effective.

Typically, you can use deserialized objects just as you would use live
objects, but you must be aware of their limitations. Also, the objects
that are returned by the Invoke-Command cmdlet have additional properties
that help you to determine the origin of the command.

Some object types, such as DirectoryInfo objects and GUIDs, are converted
back into live objects when they are received. These objects do not need
any special handling or formatting.

For information about interpreting and formatting remote output, see
about_remote_Output.

CAN I RUN BACKGROUND JOBS REMOTELY?

Yes. A Windows PowerShell background job is a Windows PowerShell
command that runs asynchronously without interacting with the session. When
you start a background job, the command prompt returns immediately, and you
can continue to work in the session while the job runs even if it runs for
an extended period of time.

You can start a background job even while other commands are running because
background jobs always run asynchronously in a temporary session.

You can run background jobs on a local or remote computer. By default, a
background job runs on the local computer. However, you can use the AsJob
parameter of the Invoke-Command cmdlet to run any remote command as a
background job. And, you can use Invoke-Command to run a Start-Job
command remotely.

For more information about background jobs in Windows PowerShell,
see about_jobs and about_remote_Jobs.

CAN I RUN WINDOWS PROGRAMS ON A REMOTE COMPUTER?

    You can use Windows PowerShell remote commands to run Windows-based
    programs on remote computers. For example, you can run Shutdown.exe
    or Ipconfig on a remote computer.

    However, you cannot use Windows PowerShell commands to open the user
    interface for any program on a remote computer.

    When you start a Windows program on a remote computer, the command is
    not completed, and the Windows PowerShell command prompt does not return,
    until the program is finished or until you press CTRL+C to interrupt the
    command. For example, if you run the IpConfig program on a remote computer,
    the command prompt does not return until IpConfig is completed.

    If you use remote commands to start a program that has a user interface,
    the program process starts, but the user interface does not appear. The
    Windows PowerShell command is not completed, and the command prompt does
    not return until you stop the program process or until you press CTRL+C,
    which interrupts the command and stops the process.

    For example, if you use a Windows PowerShell command to run Notepad on a
    remote computer, the Notepad process starts on the remote computer, but
    the Notepad user interface does not appear. To interrupt the command and
    restore the command prompt, press CTRL+C.

CAN I LIMIT THE COMMANDS THAT USERS CAN RUN REMOTELY ON MY COMPUTER?

    Yes. Every remote session must use one of the session configurations
    on the remote computer. You can manage the session configurations on
    your computer (and the permissions to those session configurations)
    to determine who can run commands remotely on your computer and which
    commands they can run.

    A session configuration configures the Environment for the session.
    You can define the configuration by using an assembly that implements
    a new configuration class or by using a script that runs in the session.
    The configuration can determine the commands that are available in the
    session. And, the configuration can include settings that protect the
    computer, such as settings that limit the amount of data that the session
    can receive remotely in a single object or command. You can also specify
    a security descriptor that determines the permissions that are required
    to use the configuration.

    The Enable-PSRemoting cmdlet creates a default session configuration
    on your computer, Microsoft.PowerShell (and Microsoft.PowerShell32 on
    64-bit operating systems). Enable-PSRemoting sets the security descriptor
    for the configuration to allow only members of the Administrators group
    on your computer to use them.

    You can use the session configuration cmdlets to edit the default
    session configurations, to create new session configurations, and to change
    the security descriptors of all the session configurations.

    When users use the Invoke-Command, New-PSSession, or Enter-PSSession
    cmdlets, they can use the ConfigurationName parameter to indicate the
    session configuration that is used for the session. And, they can change
    the default configuration that their sessions use by changing the value
    of the $PSSessionConfigurationName preference Variable in the session.

    For more information about session configurations, see the Help for
    the session configuration cmdlets. To find the session configuration
    cmdlets, type:

    Get-Command *pssessionconfiguration

WHAT ARE FAN-IN AND FAN OUT CONFIGURATIONS?

The most common Windows PowerShell remoting scenario involving
multiple computers is the one-to-many configuration, in which one
local computer (the administrator’s computer) runs Windows PowerShell
commands on numerous remote computers. This is known as the
“fan-out” scenario.

However, in some enterprises, the configuration is many-to-one, where
many client computers connect to a single remote computer that is
running Windows PowerShell, such as a file server or a kiosk.
This is known as the “fan-in” configuration.

Windows PowerShell remoting supports both fan-out and fan-in
configurations.

For the fan-out configuration, Windows PowerShell uses the Web Services for
Management (WS-Management) protocol and the WinRM service that supports the
Microsoft implementation of WS-Management. When a local computer connects to
a remote computer, WS-Management establishes a connection and uses a plug-in
for Windows PowerShell to start the Windows PowerShell host process
(Wsmprovhost.exe) on the remote computer. The user can specify an alternate
port, an alternate session configuration, and other features to customize
the remote connection.

To support the “fan-in” configuration, Windows PowerShell uses Internet
Information Services (IIS) to host WS-Management, to load the Windows
PowerShell plug-in, and to start Windows PowerShell. In this scenario,
instead of starting each Windows PowerShell session in a separate process,
all Windows PowerShell sessions run in the same host process.

IIS hosting and fan-in remote management is not supported in Windows XP or
in Windows Server 2003.

In a fan-in configuration, the user can specify a connection URI and an
HTTP endpoint, including the transport, computer name, port, and application
name. IIS forwards all the requests with a specified application name to the
application. The default is WS-Management, which can host Windows
PowerShell.

You can also specify an authentication mechanism and prohibit or allow
redirection from HTTP and HTTPS endpoints.

CAN I TEST REMOTING ON A SINGLE COMPUTER (NOT IN A DOMAIN)?

    Yes. Windows PowerShell remoting is available even when the local
    computer is not in a domain. You can use the remoting features to
    connect to sessions and to create sessions on the same computer. The
    features work the same as they do when you connect to a remote computer.

    To run remote commands on a computer in a workgroup, change the
    following Windows settings on the computer.

    Caution: These settings affect all users on the system and they can
             make the system more vulnerable to a malicious attack. Use
             caution when making these changes.

    — Windows XP with SP2:

        Use Local Security Settings (Secpol.msc) to change the setting of the
        “Network Access: Sharing and security model for local accounts” policy
        in Security Settings\Local Policies\Security Options to “Classic”.

    — Windows Vista:

        Create the following Registry entry, and then set its value to 1:
        LocalAccountTokenFilterPolicy in
        HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

        You can use the following Windows PowerShell command to add this entry:

        New-Itemproperty `
        â€“path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System `
        â€“name LocalAccountTokenFilterPolicy –propertyType DWord –value 1

    — Windows 2003:

        No changes are needed because the default setting of the
        “Network Access: Sharing and security model for local accounts” policy
        is “Classic”. Verify the setting in case it has changed.

CAN I RUN REMOTE COMMANDS ON A COMPUTER IN ANOTHER DOMAIN?

    Yes. Typically, the commands run without error, although you might need
    to use the Credential parameter of the Invoke-Command, New-PSSession,
    or Enter-PSSession cmdlets to provide the credentials of a member of the
    Administrators group on the remote computer. This is sometimes required
    even when the current user is a member of the Administrators group on the
    local and remote computers.

    However, if the remote computer is not in a domain that the local computer
    trusts, the remote computer might not be able to authenticate the user’s
    credentials.

    To enable authentication, use the following command to add the remote
    computer to the list of trusted hosts for the local computer in WinRM.
    Type the command at the Windows PowerShell prompt.

        Set-Item WSMan:\localhost\Client\TrustedHosts -value <Remote-computer-name>

    For example, to add the Server01 computer to the list of trusted hosts
    on the local computer, type the following command at the Windows
    PowerShell prompt:

        Set-Item WSMan:\localhost\Client\TrustedHosts -value Server01

SEE ALSO
    about_remote
    about_profiles
    about_pssessions
    about_remote_Jobs
    Invoke-Command
    New-PSSession

about_remote_jobs

TOPIC
    about_remote_Jobs

SHORT DESCRIPTION
    Describes how to run background jobs on remote computers.

DETAILED DESCRIPTION
    A background job is a command that runs asynchronously without interacting
    with the current session. The command prompt returns immediately, and you
    can continue to use the session while the job runs.

    By default, background jobs run on the local computer. However, you can
    use several different procedures to run background jobs on remote
    computers.

    This topic explains how to run a background job on a remote computer. For
    information about how to run background jobs on a local computer, see
    about_jobs. For more information about background jobs, see
    about_job_details.

REMOTE BACKGROUND JOBS

    You can run background jobs on remote computers by using three different
    methods.

    — Start an interactive session with a remote computer, and start a job
     in the interactive session. The procedures are the same as running a
     local job, although all actions are performed on the remote computer.

    — Run a background job on a remote computer that returns its results to
     the local computer. Use this method when you want to collect the
     results of background jobs and maintain them in a central location on
     the local computer.

    — Run a background job on a remote computer that maintains its results
     on the remote computer. Use this method when the job data is more
     securely maintained on the originating computer.

START A BACKGROUND JOB IN AN INTERACTIVE SESSION

    You can start an interactive session with a remote computer and then
    start a background job during the interactive session. For more
    information about interactive sessions, see about_remote, and
    see Enter-PSSession.

    The procedure for starting a background job in an interactive session is
    almost identical to the procedure for starting a background job on the
    local computer. However, all of the operations occur on the remote
    computer, not the local computer.

    STEP 1: Enter-PSSession

    Use the Enter-PSSession cmdlet to start an interactive session with a
    remote computer. You can use the ComputerName parameter of Enter-PSSession
    to establish a temporary connection for the interactive session. Or, you
    can use the Session parameter to run the interactive session in a Windows
    PowerShell session (PSSession).

    The following command starts an interactive session on the Server01
    computer.

        C:\PS> Enter-PSSession -computername Server01

    The command prompt changes to show that you are now connected to the
    Server01 computer.

        Server01\C:>

    STEP 2: Start-Job

    To start a background job in the session, use the Start-Job cmdlet.

    The following command runs a background job that gets the events in the
    Windows PowerShell event log on the Server01 computer. The Start-Job
    cmdlet returns an object that represents the job.

    This command saves the job object in the $job Variable.

        Server01\C:> $job = Start-Job -scriptblock {Get-Eventlog “Windows PowerShell”}

    While the job runs, you can use the interactive session to run other
    commands, including other background jobs. However, you must keep the
    interactive session open until the job is completed. If you end the
    session, the job is interrupted, and the results are lost.

    STEP 3: Get-Job

    To find out if the job is complete, display the value of the $job Variable,
    or use the Get-Job cmdlet to get the job. The following command uses the
    Get-Job cmdlet to display the job.

        Server01\C:> Get-Job $job

        SessionId Name State     HasMoreData Location Command
        ——— —- —–     ———– ——– ——-
        1         Job1 Complete True         localhost Get-Eventlog “Windows PowerShell”

    The Get-Job output shows that job is running on the “localhost” computer
    because the job was started on and is running on the same computer (in
    this case, Server01).

    STEP 4: Receive-Job

    To get the results of the job, use the Receive-Job cmdlet. You can display
    the results in the interactive session or save them to a file on the remote
    computer. The following command gets the results of the job in the $job
    Variable. The command uses the redirection operator (>) to save the results
    of the job in the PsLog.txt file on the Server01 computer.

        Server01\C:> Receive-Job $job > c:\logs\PsLog.txt

    STEP 5: Exit-PSSession

    To end the interactive session, use the Exit-PSSession cmdlet. The command
    prompt changes to show that you are back in the original session on the
    local computer.

        Server01\C:> Exit-PSSession
        C:\PS>

    STEP 6: Invoke-Command: GET CONTENT

    To view the contents of the PsLog.txt file on the Server01 computer at any
    time, start another interactive session, or run a remote command. This type
    of command is best run in a PSSession (a persistent connection) in case you
    want to use several commands to investigate and manage the data in the
    PsLog.txt file. For more information about PSSessions,
    see about_pssessions.

    The following commands use the New-PSSession cmdlet to create a PSSession
    that is connected to the Server01 computer, and they use the Invoke-Command
    cmdlet to run a Get-Content command in the PSSession to view the contents
    of the file.

        C:\PS> $s = New-PSSession -computername Server01
        C:\PS> Invoke-Command -session $s -scriptblock {Get-Content c:\logs\pslog.txt}

START A REMOTE JOB THAT RETURNS THE RESULTS TO THE LOCAL COMPUTER (ASJOB)

    To start a background job on a remote computer that returns the command
    results to the local computer, use the AsJob parameter of a cmdlet such
    as the Invoke-Command cmdlet.

    When you use the AsJob parameter, the job object is actually created on
    the local computer even though the job runs on the remote computer. When
    the job is completed, the results are returned to the local computer.

    You can use the cmdlets that contain the Job noun (the Job cmdlets) to
    manage any job created by any cmdlet. Many of the cmdlets that have
    AsJob parameters do not use Windows PowerShell remoting, so
    you can use them even on computers that are not configured for
    remoting and that do not meet the requirements for remoting.

    STEP 1: Invoke-Command -ASJOB

    The following command uses the AsJob parameter of Invoke-Command to start
    a background job on the Server01 computer. The job runs a Get-Eventlog
    command that gets the events in the System log. You can use the JobName
    parameter to assign a display name to the job.

     Invoke-Command -computername Server01 -scriptblock {Get-Eventlog system} -asjob

    The results of the command resemble the following sample output.

     SessionId Name    State     HasMoreData     Location Command
     ——— —-    —–     ———–     ——– ——-
     1         Job1    Running    True            Server01 Get-Eventlog system

    When the AsJob parameter is used, Invoke-Command returns the same type of
    job object that Start-Job returns. You can save the job object in a
    Variable, or you can use a Get-Job command to get the job.

    Note that the value of the Location property shows that the job ran on the
    Server01 computer.

    STEP 2: Get-Job

    To manage a job started by using the AsJob parameter of the Invoke-Command
    cmdlet, use the Job cmdlets. Because the job object that represents the
    remote job is on the local computer, you do not need to run remote commands
    to manage the job.

    To determine whether the job is complete, use a Get-Job command. The
    following command gets all of the jobs that were started in the current
    session.

        Get-Job

    Because the remote job was started in the current session, a local Get-Job
    command gets the job. The State property of the job object shows that the
    command was completed successfully.

     SessionId Name State     HasMoreData     Location Command
     ——— —- —–     ———–     ——– ——-
     1         Job1 Completed True            Server01 Get-Eventlog system

    STEP 3: Receive-Job

    To get the results of the job, use the Receive-Job cmdlet. Because the job
    results are automatically returned to the computer where the job object
    resides, you can get the results with a local Receive-Job command.

    The following command uses the Receive-Job cmdlet to get the results of the
    job. It uses the session ID to identify the job. This command saves the job
    results in the $results Variable. You can also redirect the results to a
    file.

     $results = Receive-Job -id 1

START A REMOTE JOB THAT KEEPS THE RESULTS ON THE REMOTE COMPUTER

    To start a background job on a remote computer that keeps the command
    results on the remote computer, use the Invoke-Command cmdlet to run
    a Start-Job command on a remote computer. You can use this method to run
    background jobs on multiple computers.

    When you run a Start-Job command remotely, the job object is created on the
    remote computer, and the job results are maintained on the remote computer.
    From the perspective of the job, all operations are local. You are just
    running commands remotely to manage a local job on the remote computer.

    STEP 1: Invoke-Command Start-Job

    Use the Invoke-Command cmdlet to run a Start-Job command on a remote
    computer.

    This command requires a PSSession (a persistent connection). If you use
    the ComputerName parameter of Invoke-Command to establish a temporary
    connection, the Invoke-Command command is considered to be complete when
    the job object is returned. As a result, the temporary connection is
    closed, and the job is canceled.

    The following command uses the New-PSSession cmdlet to create a PSSession
    that is connected to the Server01 computer. The command saves the PSSession
    in the $s Variable.

        $s = New-PSSession -computername Server01

    The next command uses the Invoke-Command cmdlet to run a Start-Job command
    in the PSSession. The Start-Job command and the Get-Eventlog command are
    enclosed in braces.

     Invoke-Command -session $s -scriptblock {Start-Job -scriptblock {Get-Eventlog system}}

    The results resemble the following sample output.

     Id     Name    State     HasMoreData     Location Command
     —     —-    —–     ———–     ——– ——-
     2        Job2    Running    True            Localhost Get-Eventlog system

    When you run a Start-Job command remotely, Invoke-Command returns the same
    type of job object that Start-Job returns. You can save the job object in
    a Variable, or you can use a Get-Job command to get the job.

    Note that the value of the Location property shows that the job ran on the
    local computer, known as “LocalHost”, even though the job ran on the
    Server01 computer. Because the job object is created on the Server01
    computer and the job runs on the same computer, it is considered to
    be a local background job.

    STEP 2: Invoke-Command Get-Job

    To manage a remote background job, use the Job cmdlets. Because the job
    object is on the remote computer, you need to run remote commands to get,
    stop, wait for, or retrieve the job results.

    To see if the job is complete, use an Invoke-Command command to run a
    Get-Job command in the PSSession that is connected to the Server01
    computer.

        Invoke-Command -session $s -scriptblock {Get-Job}

    The command returns a job object. The State property of the job object
    shows that the command was completed successfully.

     SessionId     Name    State     HasMoreData     Location Command
     ———     —-    —–     ———–     ——– ——-
     2             Job2    Completed True            LocalHost Get-Eventlog system

    STEP 3: Invoke-Command Receive-Job

    To get the results of the job, use the Invoke-Command cmdlet to run a
    Receive-Job command in the PSSession that is connected to the Server01
    computer.

    The following command uses the Receive-Job cmdlet to get the results of
    the job. It uses the session ID to identify the job. This command saves
    the job results in the $results Variable. It uses the Keep parameter of
    Receive-Job to keep the result in the job cache on the remote
    computer.

        $results = Invoke-Command -session $s -scriptblock {Receive-Job -sessionid 2 -keep}

    You can also redirect the results to a file on the local or remote
    computer. The following command uses a redirection operator to save the
    results in a file on the Server01 computer.

        Invoke-Command -session $s -command {Receive-Job -sessionid 2 > c:\logs\pslog.txt}

SEE ALSO
    about_jobs
    about_job_details
    about_remote
    Invoke-Command
    Start-Job
    Get-Job
    Wait-Job
    Stop-Job
    Remove-Job
    New-PSSession
    Enter-PSSession
    Exit-PSSession

about_remote_output

TOPIC
    about_remote_Output

SHORT DESCRIPTION
    Describes how to interpret and format the output of remote commands.

LONG DESCRIPTION
    The output of a command that was run on a remote computer might look
    like output of the same command run on a local computer, but there are
    some significant differences.

    This topic explains how to interpret, format, and display the output
    of commands that are run on remote computers.

DISPLAYING THE COMPUTER NAME

    When you use the Invoke-Command cmdlet to run a command on a remote
    computer, the command returns an object that includes the name of
    the computer that generated the data. The remote computer name is
    stored in the PSComputerName property.

    For many commands, the PSComputerName is displayed by default. For
    example, the following command runs a Get-Culture command on two
    remote computers, Server01 and Server02. The output, which appears
    below, includes the names of the remote computers on which the command
    ran.

        C:\PS> Invoke-Command -script {Get-Culture} -comp Server01, Server02

        LCID Name    DisplayName                PSComputerName
        —- —-    ———–                ————–
        1033 en-US English (United States)    Server01
        1033 es-AR Spanish (Argentina)        Server02

    You can use the HideComputerName parameter of Invoke-Command to hide
    the PSComputerName property. This parameter is designed for commands
    that collect data from only one remote computer.

    The following command runs a Get-Culture command on the Server01
    remote computer. It uses the HideComputerName parameter to hide the
    PSComputerName property and related properties.

        C:\PS> Invoke-Command -scr {Get-Culture} -comp Server01 -HideComputerName

        LCID             Name             DisplayName
        —-             —-             ———–
        1033             en-US            English (United States)

     You can also display the PSComputerName property if it is not displayed
     by default.

     For example, the following commands use the Format-Table cmdlet to add
     the PSComputerName property to the output of a remote Get-Date command.

        C:\PS> $dates = Invoke-Command -script {Get-Date} -computername Server01, Server02
        C:\PS> $dates | Format-Table DateTime, PSComputerName -auto

        DateTime                            PSComputerName
        ——–                            ————–
        Monday, July 21, 2008 7:16:58 PM    Server01
        Monday, July 21, 2008 7:16:58 PM    Server02

DISPLAYING THE MACHINENAME PROPERTY

    Several cmdlets, including Get-Process, Get-Service, and Get-EventLog,
    have a ComputerName parameter that gets the objects on a remote computer.
    These cmdlets do not use Windows PowerShell remoting, so you can use them
    even on computers that are not configured for remoting in Windows
    PowerShell.

    The objects that these cmdlets return store the name of the remote computer
    in the MachineName property. (These objects do not have a PSComputerName
    property.)

    For example, this command gets the PowerShell process on the Server01 and
    Server02 remote computers. The default display does not include the
    MachineName property.

        C:\PS> Get-Process powershell -computername server01, server02

        Handles NPM(K)    PM(K)     WS(K) VM(M) CPU(s)     Id ProcessName
        ——- ——    —–     —– —– ——     — ———–
            920     38    97524     114504 575     9.66 2648 powershell
            194     6    24256     32384 142            3020 powershell
            352     27    63472     63520 577     3.84 4796 powershell

    You can use the Format-Table cmdlet to display the MachineName property
    of the process objects.

    For example, the following command saves the processes in the $p Variable
    and then uses a pipeline operator (|) to send the processes in $p to the
    Format-Table command. The command uses the Property parameter of
    Format-Table to include the MachineName property in the display.

        C:\PS> $p = Get-Process powershell -comp Server01, Server02
        C:\PS> $P | Format-Table -property ID, ProcessName, MachineName -auto

        Id ProcessName MachineName
        — ———– ———–
        2648 powershell Server02
        3020 powershell Server01
        4796 powershell Server02

    The following more complex command adds the MachineName property to the
    default process display. It uses hash tables to specify calculated
    properties. Fortunately, you do not have to understand it to use it.

    (Note that the backtick [`] is the continuation character.)

        C:\PS> $p = Get-Process powershell -comp Server01, Server02

        C:\PS> $p | Format-Table -property Handles, `
                    @{Label=”NPM(K)”;Expression={[int]($_.NPM/1024)}}, `
                    @{Label=”PM(K)”;Expression={[int]($_.PM/1024)}}, `
                    @{Label=”WS(K)”;Expression={[int]($_.WS/1024)}}, `
                    @{Label=”VM(M)”;Expression={[int]($_.VM/1MB)}}, `
                    @{Label=”CPU(s)”;Expression={if ($_.CPU -ne $()){ $_.CPU.ToString(“N”)}}}, `
                    Id, ProcessName, MachineName -auto

        Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName MachineName
        ——- —— —– —– —– —— — ———– ———–
            920     38 97560 114532 576        2648 powershell Server02
            192     6 24132 32028 140        3020 powershell Server01
            438     26 48436 59132 565        4796 powershell Server02

DESERIALIZED OBJECTS
    When you run remote commands that generate output, the command output is
    transmitted across the network back to the local computer.

    Because most live Microsoft .NET Framework objects (such as the objects
    that Windows PowerShell cmdlets return) cannot be transmitted over the
    network, the live objects are “serialized”. In other words, the live
    objects are converted into XML representations of the object and its
    properties. Then, the XML-based serialized object is transmitted across
    the network.

    On the local computer, Windows PowerShell receives the XML-based serialized
    object and “deserializes” it by converting the XML-based object into a
    standard .NET Framework object.

    However, the deserialized object is not a live object. It is a snapshot of
    the object at the time that it was serialized, and it includes properties
    but no methods. You can use and manage these objects in Windows PowerShell,
    including passing them in pipelines, displaying selected properties, and
    formatting them.

    Most deserialized objects are automatically formatted for display by
    entries in the Types.ps1xml or Format.ps1xml files. However, the local
    computer might not have formatting files for all of the deserialized
    objects that were generated on a remote computer. When objects are
    not formatted, all of the properties of each object appear in the console
    in a streaming list.

    When objects are not formatted automatically, you can use the formatting
    cmdlets, such as Format-Table or Format-List, to format and display
    selected properties. Or, you can use the Out-GridView cmdlet to display
    the objects in a table.

    Also, if you run a command on a remote computer that uses cmdlets that you
    do not have on your local computer, the objects that the command returns
    might not be formatted properly because you do not have the formatting
    files for those objects on your computer. To get formatting data from
    another computer, use the Get-FormatData and Export-FormatData cmdlets.

    Some object types, such as DirectoryInfo objects and GUIDs, are converted
    back into live objects when they are received. These objects do not need
    any special handling or formatting.

ORDERING THE RESULTS
    The order of the computer names in the ComputerName parameter of cmdlets
    determines the order in which Windows PowerShell connects to the remote
    computers. However, the results appear in the order in which the local
    computer receives them, which might be a different order.

    To change the order of the results, use the Sort-Object cmdlet. You can
    sort on the PSComputerName or MachineName property. You can also sort on
    another property of the object so that the results from different
    computers are interspersed.

SEE ALSO
    about_remote
    Format-Table
    Get-EventLog
    Get-Process
    Get-Service
    Get-WmiObject
    Invoke-Command
    Out-GridView
    Select-Object