All posts by Adam

about_scopes

TOPIC
    about_scopes

SHORT DESCRIPTION
    Explains the concept of scope in Windows PowerShell and shows how to set
    and change the scope of elements.

LONG DESCRIPTION
    Windows PowerShell protects access to Variables, Aliases, Functions, and
    Windows PowerShell drives (PSDrives) by limiting where they can be read and
    changed. By enforcing a few simple rules for scope, Windows PowerShell
    helps to ensure that you do not inadvertently change an item that should
    not be changed.

    The following are the basic rules of scope:

        – An item you include in a scope is visible in the scope in which it
         was created and in any child scope, unless you explicitly make it
         private. You can place Variables, Aliases, Functions, or Windows
         PowerShell drives in one or more scopes.

        – An item that you created within a scope can be changed only in the
         scope in which it was created, unless you explicitly specify a
         different scope.

    If you create an item in a scope, and the item shares its name with an
    item in a different scope, the original item might be hidden under the
    new item. But, it is not overridden or changed.

Windows PowerShell Scopes

    Scopes in Windows PowerShell have both names and numbers. The named
    scopes specify an absolute scope. The numbers are relative and reflect
    the relationship between scopes.

    Global:
        The scope that is in effect when Windows PowerShell
        starts. Variables and Functions that are present when
        Windows PowerShell starts have been created in the
        global scope. This includes automatic Variables and
        preference Variables. This also includes the Variables, Aliases,
        and Functions that are in your Windows PowerShell
        profiles.

    Local:
        The current scope. The local scope can be the global
        scope or any other scope.

    Script:
        The scope that is created while a script file runs. Only
        the commands in the script run in the script scope. To
        the commands in a script, the script scope is the local
        scope.

    Private:
        Items in private scope cannot be seen outside of the current
        scope. You can use private scope to create a private version
        of an item with the same name in another scope.

    Numbered Scopes:
        You can refer to scopes by name or by a number that
        describes the relative position of one scope to another.
        Scope 0 represents the current, or local, scope. Scope 1
        indicates the immediate parent scope. Scope 2 indicates the
        parent of the parent scope, and so on. Numbered scopes
        are useful if you have created many recursive
        scopes.

Parent and Child Scopes

    You can create a new scope by running a script or Function, by creating
    a session, or by starting a new instance of Windows PowerShell. When you
    create a new scope, the result is a parent scope (the original scope) and
    a child scope (the scope that you created).

    In Windows PowerShell, all scopes are child scopes of the global scope,
    but you can create many scopes and many recursive scopes.

    Unless you explicitly make the items private, the items in the parent scope
    are available to the child scope. However, items that you create and change
    in the child scope do not affect the parent scope, unless you explicitly
    specify the scope when you create the items.

Inheritance

    A child scope does not inherit the Variables, Aliases, and Functions from
    the parent scope. Unless an item is private, the child scope can view the
    items in the parent scope. And, it can change the items by explicitly
    specifying the parent scope, but the items are not part of the child scope.

    However, a child scope is created with a set of items. Typically, it
    includes all the Aliases that have the AllScope option. This option is
    discussed later in this topic. It includes all the Variables that have the
    AllScope option, plus some Variables that can be used to customize the
    scope, such as MaximumFunctionCount.

    To find the items in a particular scope, use the Scope parameter of
    Get-Variable or Get-Alias.

    For example, to get all the Variables in the local scope, type:

    Get-Variable -scope local

    To get all the Variables in the global scope, type:

    Get-Variable -scope global

Scope Modifiers

    To specify the scope of a new Variable, Alias, or Function, use a scope
    modifier. The valid values of a modifier are Global and Script.

    The syntax for a scope modifier in a Variable is:

        $[<scope-modifier>]:<name> = <value>

    The syntax for a scope modifier in a Function is:

        Function [<scope-modifier>]:<name> {<function-body>}

    The default scope for scripts is the script scope. The default scope for
    Functions and Aliases is the local scope, even if they are defined in a
    script.

    The following command, which does not use a scope modifier, creates a
    Variable in the current or local scope:

     $a = “one”

    To create the same Variable in the global scope, use the Global scope
    modifier:

     $global:a = “one”

    To create the same Variable in the script scope, use the script
    scope modifier:

     $script:a = “one”

    You can also use a scope modifier in Functions. The following Function
    definition creates a Function in the global scope:

     Function global:Hello
     {
        Write-Host “Hello, World”
     }

    You can also use scope modifiers to refer to a Variable in a different
    scope. The following command refers to the $test Variable, first in the
    local scope and then in the global scope:

     $test

     $global:test

The AllScope Option

    Variables and Aliases have an Option property that can take a value of
    AllScope. Items that have the AllScope property become part of any child
    scopes that you create, although they are not retroactively inherited by
    parent scopes.

    An item that has the AllScope property is visible in the child scope, and
    it is part of that scope. Changes to the item in any scope affect all the
    scopes in which the Variable is defined.

Managing Scope

    Several cmdlets have a Scope parameter that lets you get or set (create
    and change) items in a particular scope. Use the following command to find
    all the cmdlets in your session that have a Scope parameter:

         Get-Help * -parameter scope

    To find the Variables that are visible in a particular scope, use the
    Scope parameter of Get-Variable. The visible parameters include global
    parameters, parameters in the parent scope, and parameters in the current
    scope.

    For example, the following command gets the Variables that are visible in
    the local scope:

        Get-Variable -scope local

    To create a Variable in a particular scope, use a scope modifier or the
    Scope parameter of Set-Variable. The following command creates a Variable
    in the global scope:

    New-Variable -scope global -name a -value “One”

    You can also use the Scope parameter of the New-Alias, Set-Alias, or
    Get-Alias cmdlets to specify the scope. The following command creates an
    Alias in the global scope:

    New-Alias -scope global -name np -value Notepad.exe

    To get the Functions in a particular scope, use the Get-Item cmdlet when
    you are in the scope. The Get-Item cmdlet does not have a scope parameter.

Using Dot Source Notation with Scope

    Scripts and Functions follow all the rules of scope. You create them in a
    particular scope, and they affect only that scope unless you use a cmdlet
    parameter or a scope modifier to change that scope.

    But, you can add a script or Function to the current scope by using dot
    source notation. Then, when a script runs in the current scope, any
    Functions, Aliases, and Variables that the script creates are available
    in the current scope.

    To add a Function to the current scope, type a dot (.) and a space before
    the path and name of the Function in the Function call.

    For example, to run the Sample.ps1 script from the C:\Scripts directory in
    the script scope (the default for scripts), use the following command:

        c:\scripts\sample.ps1

    To run the Sample.ps1 script in the local scope, use the following command:

        . c:\scripts.sample.ps1

    When you use the call operator (&) to run a Function or script, it is not
    added to the current scope. The following example uses the call operator:

        & c:\scripts.sample.ps1

    Any Aliases, Functions, or Variables that the Sample.ps1 script creates
    are not available in the current scope.

Restricting Without Scope

    A few Windows PowerShell concepts are similar to scope or interact with
    scope. These concepts may be confused with scope or the behavior of scope.

    Sessions, modules, and nested prompts are self-contained Environments,
    but they are not child scopes of the global scope in the session.

    Sessions:
        A session is an Environment in which Windows PowerShell runs.
        When you create a session on a remote computer, Windows
        PowerShell establishes a persistent connection to the remote
        computer. The persistent connection lets you use the session for
        multiple related commands.

        Because a session is a contained Environment, it has its own
        scope, but a session is not a child scope of the session in
        which is was created. The session starts with its own global
        scope. This scope is independent of the global scope of the session.
        You can create child scopes in the session. For example, you can run
        a script to create a child scope in a session.

    Modules:
        You can use a Windows PowerShell module to share and deliver
        Windows PowerShell tools. A module is a unit that can contain
        cmdlets, scripts, Functions, Variables, Aliases, and other useful
        items. Unless explicitly defined, the items in a module are not
        accessible outside the module. Therefore, you can add the module to
        your session and use the public items without worrying that the
        other items might override the cmdlets, scripts, Functions, and other
        items in your session.

        The privacy of a module behaves like a scope, but adding a module
        to a session does not change the scope. And, the module does not have
        its own scope, although the scripts in the module, like all Windows
        PowerShell scripts, do have their own scope.

    Nested Prompts:
        Similarly, nested prompts do not have their own scope. When you enter
        a nested prompt, the nested prompt is a subset of the Environment.
        But, you remain within the local scope.

        Scripts do have their own scope. If you are debugging a script, and
        you reach a breakpoint in the script, you enter the script scope.

    Private Option:
        Aliases and Variables have an Option property that can take a value
        of Private. Items that have the Private option can be viewed and
        changed in the scope in which they are created, but they cannot be
        viewed or changed outside that scope.

        For example, if you create a Variable that has a private option in the
        global scope and then run a script, Get-Variable commands in the script
        do not display the private Variable. This occurs even if you use
        the global scope modifier.

        You can use the Option parameter of the New-Variable, Set-Variable,
        New-Alias, and Set-Alias cmdlets to set the value of the Option
        property to Private.

    Visibility:
        The Visibility property of a Variable or Alias determines whether you
        can see the item outside the container, such as a module, in which it
        was created. Visibility is designed for containers in the same way that
        the Private value of the Option property is designed for scopes.

        The Visibility property takes the Public and Private values. Items
        that have private visibility can be viewed and changed only in the
        container in which they were created. If the container is added or
        imported, the items that have private visibility cannot be viewed or
        changed.

        Because Visibility is designed for containers, it works differently
        in a scope. If you create an item that has private visibility in the
        global scope, you cannot view or change the item in any scope. If you
        try to view or change the value of a Variable that has private
        visibility, Windows PowerShell returns an error message.

        You can use the New-Variable and Set-Variable cmdlets to create a
        Variable that has private visibility.

EXAMPLES

Example 1: Change a Variable Value Only in a Script

     The following command changes the value of the $ConfirmPreference
     Variable in a script. The change does not affect the global scope.

     First, to display the value of the $ConfirmPreference Variable in
     the local scope, use the following command:

         C:\PS> $ConfirmPreference
         High

     Create a Scope.ps1 script that contains the following commands:

         $ConfirmPreference = “Low”
         “The value of `$ConfirmPreference is $ConfirmPreference.”

     Run the script. The script changes the value of the $ConfirmPreference
     Variable and then reports its value in the script scope. The output
     should resemble the following output:

         The value of $ConfirmPreference is Low.

     Next, test the current value of the $ConfirmPreference Variable in the
     current scope.

         C:\PS> $ConfirmPreference
         High

     This example shows that changes to the value of a Variable in the script
     scope do not affect the value of that Variable in the parent scope.

Example 2: View a Variable Value in Different Scopes

     You can use scope modifiers to view the value of a Variable in the local
     scope and in a parent scope.

     First, define a $test Variable in the global scope.

     $test = “Global”

     Next, create a Sample.ps1 script that defines the $test
     Variable. In the script, use a scope modifier to refer
     to either the global or local versions of the $test Variable.

         # In Sample.ps1

         $test = “Local”
         “The local value of `$test is $test.”
         “The global value of `$test is $global:test.”

     When you run Sample.ps1, the output should resemble the following output:

         The local value of $test is Local.
         The global value of $test is Global.

     When the script is complete, only the global value of $test is defined
     in the session.

         C:\PS> $test
         Global

Example 3: Change the Value of a Variable in a Parent Scope

     Unless you protect an item by using the Private option or another
     method, you can view and change the value of a Variable in a parent
     scope.

     First, define a $test Variable in the global scope.

     $test = “Global”

     Next, create a Sample.ps1 script that defines the $test Variable. In the
     script, use a scope modifier to refer to either the global or local
     versions of the $test Variable.

         # In Sample.ps1

         $global:test = “Local”
         “The global value of `$test is $global:test.”

     When the script is complete, the global value of $test is changed.

         C:\PS> $test
         Local

Example 4: Creating a Private Variable

     A private Variable is a Variable that has an Option property that has a
     value of Private. Private Variables are inherited by the child scope, but
     they can be viewed or changed only in the scope in which they were
     created.

     The following command creates a private Variable called $ptest in the
     local scope.

     New-Variable -name ptest -value 1 -option private

     You can display and change the value of $ptest in the local scope.

     C:\PS> $ptest
         1
         C:\PS> $ptest = 2
         C:\PS> $ptest
     2

     Next, create a Sample.ps1 script that contains the following commands.
     The command tries to display and change the value of $ptest.

         # In Sample.ps1

         “The value of `$Ptest is $Ptest.”
          “The value of `$Ptest is $global:Ptest.”

     Because the $ptest Variable is not visible in the script scope, the
     output is empty.

         “The value of $Ptest is .”
          “The value of $Ptest is .”

SEE ALSO
    about_Variables
    about_environment_variables
    about_functions
    about_script_blocks

about_Return

TOPIC
    about_Return

SHORT DESCRIPTION
    Exits the current scope, which can be a Function, script, or script block.

LONG DESCRIPTION
    The Return keyword exits a Function, script, or script block. It can be
    used to exit a scope at a specific point, to return a value, or to indicate
    that the end of the scope has been reached.

    Users who are familiar with languages like C or C# might want to use the
    Return keyword to make the logic of leaving a scope explicit.

    In Windows PowerShell, the results of each statement are returned as
    output, even without a statement that contains the Return keyword.
    Languages like C or C# return only the value or values that are specified
    by the Return keyword.

Syntax

     The syntax for the Return keyword is as follows:

         return [<expression>]

     The Return keyword can appear alone, or it can be followed by a value or
     expression, as follows:

         return
         return $a
         return (2 + $a)

Examples

     The following example uses the Return keyword to exit a Function at a
     specific point if a conditional is met:

         Function ScreenPassword($instance)
         {
             if (!($instance.screensaversecure)) {return $instance.name}
             <additional statements>
         }

         foreach ($a in @(Get-WmiObject win32_desktop)) { ScreenPassword($a) }

     This script checks each user account. The ScreenPassword Function returns
     the name of any user account that does not have a password-protected
     screen saver. If the screen saver is password protected, the Function
     completes any other statements to be run, and Windows PowerShell does not
     return any value.

     In Windows PowerShell, values can be returned even if the Return keyword
     is not used. The results of each statement are returned. For example, the
     following statements return the value of the $a Variable:

         $a
         return

     The following statement also returns the value of $a:

         return $a

     The following example includes a statement intended to let the user know
     that the Function is performing a calculation:

         Function calculation {
             param ($value)

             “Please wait. Working on calculation…”
             $value += 73
             return $value
             }

     Running this Function and assigning the result to a Variable has the
     following effect:

         C:\PS> $a = calculation 14
         C:\PS>

     The “Please wait. Working on calculation…” string is not displayed.
     Instead, it is assigned to the $a Variable, as in the following example:

         C:\PS> $a
         Please wait. Working on calculation…
         87

     Both the informational string and the result of the calculation are
     returned by the Function and assigned to the $a Variable.

SEE ALSO
    about_functions
    about_scopes
    about_script_blocks

about_Reserved_Words

TOPIC
    about_Reserved_Words

SHORT DESCRIPTION
    Lists the reserved words that cannot be used as identifiers because they
    have a special meaning in Windows PowerShell.

LONG DESCRIPTION
    There are certain words that have special meaning in Windows PowerShell.
    When these words appear without quotation marks, Windows PowerShell
    attempts to apply their special meaning rather than treating them as
    character strings. To use these words as parameter arguments in a command
    or script without invoking their special meaning, enclose the reserved
    words in quotation marks.

    The following are the reserved words in Windows PowerShell:

        Break
        Continue
        Do
        Else
        Elseif
        Filter
        For
        Foreach
        Function
        If
        In
        Local
        Private
        Return
        Switch
        Until
        Where
        While

    For information about language statements, such as Foreach, If,
    For, and While, type “Get-Help“, type the prefix “about_”, and then type
    the name of the statement. For example, to get information about the
    Foreach statement, type:

    Get-Help about_Foreach

    For information about the Filter statement or the Return statement
    syntax, type:

        Get-Help about_functions

SEE ALSO
    about_Command_Syntax
    about_escape_characters
    about_Language_Keywords
    about_Parsing
    about_Quoting_Rules
    about_script_blocks
    about_Special_Characters

about_requires

TOPIC
    about_requires

SHORT DESCRIPTION
    Prevents a script from running by requiring the specified snap-ins and
    version.

LONG DESCRIPTION
    The #Requires statement prevents a script from running unless the Windows
    PowerShell version, snap-in, and snap-in version prerequisites are met. If
    the prerequisites are not met, Windows PowerShell does not run the script.

    You can use #Requires statements in any script. You cannot use them in
    Functions, cmdlets, or snap-ins.

Syntax

     Use the following syntax to specify the snap-in and the version of the
     snap-in that you want to require:

         #requires –PsSnapIn <PsSnapIn> [-Version <N>[.<n>]]

     Use the following syntax to specify the minimum version of
     Windows PowerShell that you want to require:

         #requires -Version <N>[.<n>]

     Use the following syntax to specify the shell that you want to require:

         #requires –ShellId <ShellId>

Rules for Use

     – The #Requires statement must be the first item on a line in a script.

     – A script can include more than one #Requires statement.

     – The #Requires statements can appear on any line in a script.

Examples

     The following statement requires the Microsoft.PowerShell.Security
     snap-in:

         #requires –PsSnapIn Microsoft.PowerShell.Security

     If the Microsoft.PowerShell.Security snap-in is not loaded, the script
     does not run, and Windows PowerShell displays the following error
     message:

         “The script ‘<script-name>’ cannot be run because the following
         Windows PowerShell snap-ins that are specified by its “#requires”
         statements are missing: Microsoft.PowerShell.Security.”

     The following statement requires the Windows PowerShell 2.0 version or
     any later version of the Microsoft.PowerShell.Security snap-in:

         #requires –PsSnapIn Microsoft.PowerShell.Security –Version 2

     The following statement requires Windows PowerShell 2.0 or a later
     version:

         #requires –Version 2.0

     The following script has two #Requires statements. The requirements
     specified in both statements must be met. Otherwise, the script will not
     run. Each #Requires statement must be the first item on a line:

         #requires –PsSnapIn Microsoft.PowerShell.Security –Version 2
         Get-WmiObject WIN32_LogicalDisk | Out-File K:\status\DiskStatus.txt
         #requires –Version 2

     The following #Requires statement prevents a script from running if the
     specified shell ID does not match the current shell ID. The current
     shell ID is stored in the $ShellId Variable:

         #requires –ShellId MyLocalShell

SEE ALSO
    about_Automatic_Variables
    about_Language_Keywords
    about_PSSnapins
    Get-PSSnapin

about_remote_troubleshooting

TOPIC
    about_remote_TroubleShooting

SHORT DESCRIPTION
    Describes how to troubleshoot remote operations in Windows PowerShell.

LONG DESCRIPTION
    This section describes some of the problems that you might encounter when
    using the remoting features of Windows PowerShell that are based on
    WS-Management technology and it suggests solutions to these problems.

    Before using Windows PowerShell remoting, see about_remote and
    about_remote_requirements for guidance on configuration and basic use Also,
    the Help topics for each of the remoting cmdlets, particularly the parameter
    descriptions, have useful information that is designed to help you avoid
    problems.

    Updated versions of this topic, and other Windows PowerShell help topics,
    can be found online in the Microsoft TechNet Library. To see the online
    version of this help topic, paste the following URL in your Internet
    browser:

    http://go.microsoft.com/fwlink/?LinkID=135188

    NOTE: On Windows Vista, Windows Server 2008, and later versions of Windows,
    to view or change settings for the local computer in the WSMan: drive,
    including changes to the session configurations, trusted hosts, ports, or
    listeners, start Windows PowerShell with the “Run as administrator” option.

TROUBLESHOOTING PERMISSION AND AUTHENTICATION ISSUES

    This section discusses remoting problems that are related to user and
    computer permissions and remoting requirements.

    HOW TO RUN AS ADMINISTRATOR
    —————————
        ERROR: Access is denied. You need to run this cmdlet from an elevated
        process.

    To start a remote session on the local computer, or to view or change
    settings for the local computer in the WSMan: drive, including changes
    to the session configurations, trusted hosts, ports, or listeners,
    start Windows PowerShell with the “Run as administrator” option.

    To start Windows PowerShell with the “Run as administrator option:

    — Right-click a Windows PowerShell (or Windows PowerShell ISE) icon
     and then click “Run as administrator.

    To start Windows PowerShell with the “Run as administrator option in
    Windows 7 and Windows Server 2008 R2.

    — In the Windows taskbar, right-click the Windows PowerShell icon,
     and then click “Run Windows PowerShell as admin.”

    Note: In Windows Server 2008 R2, the Windows PowerShell icon is pinned
    to the taskbar by default.

    HOW TO ENABLE REMOTING
    ———————-
        ERROR: ACCESS IS DENIED
        – or –
        ERROR: The connection to the remote host was refused. Verify that the
        WS-Management service is running on the remote host and configured to
        listen for requests on the correct port and HTTP URL.

    No configuration is required to enable a computer to send remote
    commands. However, to receive remote commands, the computer must be
    configured for remoting. The configuration includes starting the WinRM
    service, setting the startup type for the WinRM service to Automatic,
    creating listeners for HTTP and HTTPS connections, and creating default
    session configurations.

    To configure a computer to receive remote commands, use the
    Enable-PSRemoting cmdlet. The following command enables all required
    remote settings, enables the session configurations, and restarts the
    WinRM service to make the changes effective.

        Enable-PSRemoting

    To suppress all user prompts, type:

        Enable-PSRemoting -force

    For more information, see Enable-PSRemoting.

    HOW TO ENABLE REMOTING IN AN ENTERPRISE
    —————————————
        ERROR: ACCESS IS DENIED
        – or –
        ERROR: The connection to the remote host was refused. Verify that the
        WS-Management service is running on the remote host and configured to
        listen for requests on the correct port and HTTP URL.

    To enable a single computer to receive remote Windows PowerShell commands
    and accept connections, use the Enable-PSRemoting cmdlets.

    To enable remoting for multiple computers in an enterprise, you can use the
    following scaled options.

    — To configure listeners for remoting, enable the “Allow automatic
     configuration of listeners” group policy. For instructions, see
     “How to Enable Listeners by Using a Group Policy” (below).

    — To set the startup type of the Windows Remote Management (WinRM)
     to Automatic on multiple computers, use the Set-Service cmdlet. For
     instructions, see “How to Set the Startup Type of the WinrM Service”
     (below).

    — To enable a firewall exception, use the “Windows Firewall: Allow Local
     Port Exceptions” group policy. For instructions, see “How to Create a
     Firewall Exception by Using a Group Policy” (below).

    HOW TO ENABLE LISTENERS BY USING A GROUP POLICY
    ————————————————
        ERROR: ACCESS IS DENIED
        – or –
        ERROR: The connection to the remote host was refused. Verify that the
        WS-Management service is running on the remote host and configured to
        listen for requests on the correct port and HTTP URL.

    To configure the listeners for all computers in a domain, enable the “Allow
    automatic configuration of listeners” policy in the following Group Policy
    path:

        Computer Configuration\Administrative Templates\Windows Components
         \Windows Remote Management (WinRM)\WinRM service

    Enable the policy and specify the IPv4 and IPv6 filters. Wildcards (*) are
    permitted.

    HOW TO ENABLE A FIREWALL EXCEPTION BY USING A GROUP POLICY
    ———————————————————-
        ERROR: ACCESS IS DENIED
        – or –
        ERROR: The connection to the remote host was refused. Verify that the
        WS-Management service is running on the remote host and configured to
        listen for requests on the correct port and HTTP URL.

    To enable a firewall exception for in all computers in a domain, enable the
    “Windows Firewall: Allow local port exceptions” policy in the following
    Group Policy path:

        Computer Configuration\Administrative Templates\Network
         \Network Connections\Windows Firewall\Domain Profile

    This policy allows members of the Administrators group on the computer to
    use Windows Firewall in Control Panel to create a firewall exception for
    the Windows Remote Management service.

    HOW TO SET THE STARTUP TYPE OF THE WINRM SERVICE
    ————————————————
        ERROR: ACCESS IS DENIED

    Windows PowerShell remoting depends upon the Windows Remote Management
    (WinRM) service. The service must be running to support remote commands.

    On Windows Server 2003, Windows Server 2008, and Windows Server 2008 R2,
    the startup type of the Windows Remote Management (WinRM) service is
    Automatic.

    However, on Windows XP, Windows Vista, and Windows 7, the WinRM service is
    disabled by default.

    To set the startup type of a service on a remote computer, use the
    Set-Service cmdlet.

    To run the command on multiple computers, you can create a text file or
    CSV file of the computer names.

    For example, the following commands get a list of computer names from the
    Servers.txt file and then sets the startup type of the WinRM service on all
    of the computers to Automatic.

        C:\PS> $servers = Get-Content servers.txt

        C:\PS> Set-Service WinRM -computername $servers -startuptype Automatic

    To see the results use the Get-WmiObject cmdlet with the Win32_Service object.
    For more information, see Set-Service.

    HOW TO RECREATE THE DEFAULT SESSION CONFIGURATIONS
    ————————————————–
        ERROR: ACCESS IS DENIED

    To connect to the local computer and run commands remotely, the local
    computer must include session configurations for remote commands.

    When you use Enable-PSRemoting, it creates default session configurations
    on the local computer. Remote users use these session configurations
    whenever a remote command does not include the ConfigurationName parameter.

    If the default configurations on a computer are unregistered or deleted,
    use the Enable-PSRemoting cmdlet to recreate them. You can use this cmdlet
    repeatedly. It does not generate errors if a feature is already configured.

    If you change the default session configurations and want to restore the
    original default session configurations, use the
    Unregister-PSSessionConfiguration cmdlet to delete the changed session
    configurations and then use the Enable-PSRemoting cmdlet to restore them.
    Enable-PSRemoting does not change existing session configurations.

    Note: When Enable-PSRemoting restores the default session configuration, it
    does not create explicit security descriptors for the configurations.
    Instead, the configurations inherit the security descriptor of the RootSDDL,
    which is secure by default.

    To see the RootSDDL security descriptor, type:

        Get-Item WSMan:\localhost\Service\RootSDDL

    To change the RootSDDL, use the Set-Item cmdlet in the WSMan: drive. To
    change the security descriptor of a session configuration, use the
    Set-PSSessionConfiguration cmdlet with the SecurityDescriptorSDDL or
    ShowSecurityDescriptorUI parameters.

    For more information about the WSMan: drive, see the Help topic for the
    WS-Management provider (“Get-Help WSMan“).

    HOW TO PROVIDE ADMINISTRATOR CREDENTIALS
    —————————————-
        ERROR: ACCESS IS DENIED

    To create a PSSession or run commands on a remote computer, by default, the
    current user must be a member of the Administrators group on the remote
    computer. Credentials are sometimes required even when the current user is
    logged on to an account that is a member of the Administrators group.

    If the current user is a member of the Administrators group on the remote
    computer, or can provide the credentials of a member of the Administrators
    group, use the Credential parameter of the New-PSSession, Enter-PSSession
    or Invoke-Command cmdlets to connect remotely.

    For example, the following command provides the credentials of an
    Administrator.

        Invoke-Command -ComputerName Server01 -Credential Domain01\Admin01

    For more information about the Credential parameter, see New-PSSession,
    Enter-PSSession or Invoke-Command.

    HOW TO ENABLE REMOTING FOR NON-ADMINISTRATIVE USERS
    —————————————————
        ERROR: ACCESS IS DENIED

    To establish a PSSession or run a command on a remote computer, the user
    must have permission to use the session configurations on the remote
    computer.

    By default, only members of the Administrators group on a computer have
    permission to use the default session configurations. Therefore, only
    members of the Administrators group can connect to the computer remotely.

    To allow other users to connect to the local computer, give the user
    Execute permissions to the default session configurations on the local
    computer.

    The following command opens a property sheet that lets you change the
    security descriptor of the default Microsoft.PowerShell session
    configuration on the local computer.

        Set-PSSessionConfiguration Microsoft.Powershell -ShowSecurityDescriptorUI

    For more information, see about_Session_Configurations.

    HOW TO ENABLE REMOTING FOR ADMINISTRATORS IN OTHER DOMAINS
    ———————————————————-
        ERROR: ACCESS IS DENIED

    When a user in another domain is a member of the Administrators group on
    the local computer, the user cannot connect to the local computer remotely
    with Administrator privileges. By default, remote connections from other
    domains run with only standard user privilege tokens.

    However, you can use the LocalAccountTokenFilterPolicy Registry entry to
    change the default behavior and allow remote users who are members of the
    Administrators group to run with Administrator privileges.

    Caution: The LocalAccountTokenFilterPolicy entry disables user account
             control (UAC) remote restrictions for all users of all affected
             computers. Consider the implications of this setting carefully
             before changing the policy.

    To change the policy, use the following command to set the value of the
    LocalAccountTokenFilterPolicy Registry entry to 1.

        C:\PS> New-Itemproperty -name LocalAccountTokenFilterPolicy -path `
            HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -propertyType `
            DWord -value 1

    HOW TO USE AN IP ADDRESS IN A REMOTE COMMAND
    —————————————————–
        ERROR: The WinRM client cannot process the request. If the
        authentication scheme is different from Kerberos, or if the client
        computer is not joined to a domain, then HTTPS transport must be used
        or the destination machine must be added to the TrustedHosts
        configuration setting.

    The ComputerName parameters of the New-PSSession, Enter-PSSession and
    Invoke-Command cmdlets accept an IP address as a valid value. However,
    because Kerberos authentication does not support IP addresses, NTLM
    authentication is used by default whenever you specify an IP address.

    When using NTLM authentication, the following procedure is required
    for remoting.

    1. Configure the computer for HTTPS transport or add the IP addresses
     of the remote computers to the TrustedHosts list on the local
     computer.

     For instructions, see “How to Add a Computer to the TrustedHosts
     List” below.

    2. Use the Credential parameter in all remote commands.

     This is required even when you are submitting the credentials
     of the current user.

    HOW TO CONNECT REMOTELY FROM A WORKGROUP-BASED COMPUTER
    ——————————————————-
        ERROR: The WinRM client cannot process the request. If the
        authentication scheme is different from Kerberos, or if the client
        computer is not joined to a domain, then HTTPS transport must be used
        or the destination machine must be added to the TrustedHosts
        configuration setting.

    When the local computer is not in a domain, the following procedure is required
    for remoting.

    1. Configure the computer for HTTPS transport or add the names of the
     remote computers to the TrustedHosts list on the local computer.

     For instructions, see “How to Add a Computer to the TrustedHosts
     List” below.

    2. Verify that a password is set on the workgroup-based computer. If a
     password is not set or the password value is empty, you cannot run
     remote commands.

     To set password for your user account, use User Accounts in Control
     Panel.

    3. Use the Credential parameter in all remote commands.

     This is required even when you are submitting the credentials
     of the current user.

    HOW TO ADD A COMPUTER TO THE TRUSTED HOSTS LIST
    ———————————————–

    The TrustedHosts item can contain a comma-separated list of computer
    names, IP addresses, and fully-qualified domain names. Wildcards
    are permitted.

    To view or change the trusted host list, use the WSMan: drive. The
    TrustedHost item is in the WSMan:\localhost\Client node.

    Only members of the Administrators group on the computer have permission
    to change the list of trusted hosts on the computer.

    Caution: The value that you set for the TrustedHosts item affects all
             users of the computer.

    To view the list of trusted hosts, use the following command:

        Get-Item WSMan:\localhost\Client\TrustedHosts

    You can also use the Set-Location cmdlet (alias = cd) to navigate
    though the WSMan: drive to the location.
    For example: “cd WSMan:\localhost\Client; dir”.

    To add all computers to the list of trusted hosts, use the following
    command, which places a value of * (all) in the ComputerName

        Set-Item WSMan:localhost\client\trustedhosts -value *

    You can also use a wildcard character (*) to add all computers in a
    particular domain to the list of trusted hosts. For example, the following
    command adds all of the computers in the Fabrikam domain to the list of
    trusted hosts.

        Set-Item WSMan:localhost\client\trustedhosts *.fabrikam.com

    To add the names of particular computers to the list of trusted hosts, use
    the following command format:

        Set-Item WSMan:\localhost\Client\TrustedHosts -value <ComputerName>[,<ComputerName>]

    where each value <ComputerName> must have the following format:

        <Computer>.<Domain>.<Company>.<top-level-domain>

    For example:

        Set-Item WSMan:\localhost\Client\TrustedHosts -value Server01.Domain01.Fabrikam.com

    To add a computer name to an existing list of trusted hosts, first save
    the current value in a Variable, and then set the value to a
    comma-separated list that includes the current and new values.

    For example, to add the Server01 computer to an existing list of trusted
    hosts, use the following command

        $curValue = (Get-Item WSMan:\localhost\Client\TrustedHosts).value

        Set-Item WSMan:\localhost\Client\TrustedHosts -value “$curValue, Server01.Domain01.Fabrikam.com”

    To add the IP addresses of particular computers to the list of trusted hosts,
    use the following command format:

        Set-Item WSMan:\localhost\Client\TrustedHosts -value <IP Address>

    For example:

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

    To add a computer to the TrustedHosts list of a remote computer, use the
    Connect-WSMan cmdlet to add a node for the remote computer to the WSMan: drive
    on the local computer. Then use a Set-Item command to add the computer.

    For more information about the Connect-WSMan cmdlet, see Connect-WSMan.

TROUBLESHOOTING COMPUTER CONFIGURATION ISSUES
    This section discusses remoting problems that are related to particular
    configurations of a computer, domain, or enterprise.

    HOW TO CONFIGURE REMOTING ON ALTERNATE PORTS
    ——————————————–
        ERROR: The connection to the specified remote host was refused. Verify
        that the WS-Management service is running on the remote host and
        configured to listen for requests on the correct port and HTTP URL.

    Windows PowerShell remoting uses port 80 for HTTP transport by default. The
    default port is used whenever the user does not specify the ConnectionURI
    or Port parameters in a remote command.

    To change the default port that Windows PowerShell uses, use Set-Item cmdlet
    in the WSMan: drive to change the Port value in the listener leaf node.

    For example, the following command changes the default port to 8080.

        Set-Item WSMan:\localhost\listener\listener*\port -value 8080

    HOW TO CONFIGURE REMOTING WITH A PROXY SERVER
    ———————————————
        ERROR: The client cannot connect to the destination specified in the
        request. Verify that the service on the destination is running and is
        accepting requests.

    Because Windows PowerShell remoting uses the HTTP protocol, it is affected
    by HTTP proxy settings. In enterprises that have proxy servers, users
    cannot access a Windows PowerShell remote computer directly.

    To resolve this problem, use proxy setting options in your remote command.
    The following settings are available:

        — ProxyAccessType
        — ProxyAuthentication
        — ProxyCredential

    To set these options for a particular command, use the following procedure:

        1. Use the ProxyAccessType, ProxyAuthentication, and ProxyCredential
         parameters of the New-PSSessionOption cmdlet to create a session
         option object with the proxy settings for your enterprise. Save the
         option object is a Variable.

        2. Use the Variable that contains the option object as the value of the
         SessionOption parameter of a New-PSSession, Enter-PSSession, or
         Invoke-Command command.

    For example, the following command creates a session option object with
    proxy session options and then uses the object to create a remote session.

        C:\PS> $SessionOption = New-PSSessionOption -ProxyAccessType IEConfig `
                -ProxyAuthentication Negotiate -ProxyCredential Domain01\User01

        C:\PS> New-PSSession -ConnectionURI https://www.fabrikam.com

    For more information about the New-PSSessionOption cmdlet, see
    New-PSSessionOption.

    To set these options for all remote commands in the current session, use
    the option object that New-PSSessionOption creates in the value of the
    $PSSessionOption preference Variable. For more information about the
    $PSSessionOption preference Variable, see about_preference_variables.

    To set these options for all remote commands all Windows PowerShell sessions
    on the local computer, add the $PSSessionOption preference Variable to your
    Windows PowerShell profile. For more information about Windows PowerShell
    profiles, see about_profiles.

    HOW TO DETECT A 32-BIT SESSION ON A 64-BIT COMPUTER
    —————————————————
        ERROR: The term “<tool-name>” 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 try
        again.

    If the remote computer is running a 64-bit version of Windows, and the
    remote command is using a 32-bit session configuration, such as
    Microsoft.PowerShell32, Windows Remote Management (WinRM) loads a WOW64
    process and Windows automatically redirects all references to the
    %Windir%\System32 directory to the %windir%\SysWOW64 directory.

    As a result, if you try to use tools in the System32 directory that do
    not have counterparts in the SysWow64 directory, such as Defrag.exe,
    the tools cannot be found in the directory.

    To find the processor architecture that is being used in the session,
    use the value of the PROCESSOR_ARCHITECTURE Environment Variable. The
    following command finds the processor architecture of the session in the
    $s Variable.

        C:\PS> $s = New-PSSession -computername Server01 -configurationName CustomShell

        C:\PS> Invoke-Command -session $s {$env:PROCESSOR_ARCHITECTURE}
        x86

    For more information about session configurations, see
    about_Session_Configurations.

TROUBLESHOOTING POLICY AND PREFERENCE ISSUES
    This section discusses remoting problems that are related to policies and
    preferences set on the local and remote computers.

    HOW TO CHANGE THE EXECUTION POLICY FOR Import-PSSession AND Import-Module
    ————————————————————————-
        ERROR: Import-Module: File <filename> cannot be loaded because the
        execution of scripts is disabled on this system.

    The Import-PSSession and Export-PSSession cmdlets create modules that
    contains unsigned script files and formatting files.

    To import the modules that are created by these cmdlets, either by using
    Import-PSSession or Import-Module, the execution policy in the current
    session cannot be Restricted or AllSigned. (For information about Windows
    PowerShell execution policies, see about_execution_policies.

    To import the modules without changing the execution policy for the local
    computer that is set in the Registry, use the Scope parameter of
    Set-ExecutionPolicy to set a less restrictive execution policy for a single
    process.

    For example, the following command starts a process with the RemoteSigned
    execution policy. The execution policy change affects only the current
    process and does not change the Windows PowerShell ExecutionPolicy Registry
    setting.

        Set-ExecutionPolicy -scope process -executionpolicy RemoteSigned

    You can also use the ExecutionPolicy parameter of PowerShell.exe to start
    a single session with a less restrictive execution policy.

        powershell.exe -executionpolicy RemoteSigned

    For more information about the cmdlets, see Import-PSSession,
    Export-PSSession, and Import-Module. For more information about
    execution policies, see about_execution_policies. For more information
    about the PowerShell.exe console help options, type “powershell.exe -?”.

    HOW TO SET AND CHANGE QUOTAS
    —————————-
        ERROR: The total data received from the remote client exceeded allowed
        maximum.

    You can use quotas to protect the local computer and the remote computer
    from excessive resource use, both accidental and malicious.

    The following quotas are available in the basic configuration.

    — The WS-Management provider (WSMan:) provides several quota settings,
     such as the MaxEnvelopeSizeKB and MaxProviderRequests settings in the
     WSMan:\<ComputerName> node and the MaxConcurrentOperations,
     MaxConcurrentOperationsPerUser, and MaxConnections settings in the
     WSMan:\<ComputerName>\Service node.

    — You can protect the local computer by using the
     MaximumReceivedDataSizePerCommandMB and MaximumReceivedObjectSizeMB
     parameters of the New-PSSessionOption cmdlet and the $PSSessionOption
     preference Variable.

    — You can protect the remote computer by adding restrictions to the session
     configurations, such as by using the MaximumReceivedDataSizePerCommandMB
     and MaximumReceivedObjectSizeMB parameters of the
     Register-PSSessionConfiguration cmdlet.

    When quotas conflict with a command, Windows PowerShell generates an error.

    To resolve the error, change the remote command to comply with the quota.
    Or, determine the source of the quota, and then increase the quota to allow
    the command to complete.

    For example, the following command increases the object size quota in the
    Microsoft.PowerShell session configuration on the remote computer from 10 MB
    (the default value) to 11 MB.

        Set-PSSessionConfiguration -name microsoft.powershell `
            -MaximumReceivedObjectSizeMB 11 -Force

    For more information about the New-PSSsessionOption cmdlet, see
    New-PSSessionOption.

    For more information about the WS-Management quotas, see the Help topic for
    the WS-Management provider (type “Get-Help WSMan“).

    HOW TO RESOLVE TIMEOUT ERRORS
    —————————–
        ERROR: The WS-Management service cannot complete the operation within
        the time specified in OperationTimeout.

    You can use timeouts to protect the local computer and the remote computer
    from excessive resource use, both accidental and malicious. When timeouts
    are set on both the local and remote computer, Windows PowerShell uses the
    shortest timeout settings.

    The following timeouts are available in the basic configuration.

    — The WS-Management provider (WSMan:) provides several client-side and
     service-side timeout settings, such as the MaxTimeoutms setting in the
     WSMan:\<ComputerName> node and the EnumerationTimeoutms and
     MaxPacketRetrievalTimeSeconds settings in the
     WSMan:\<ComputerName>\Service node.

    — You can protect the local computer by using the CancelTimeout, IdleTimeout,
     OpenTimeout, and OperationTimeout parameters of the New-PSSessionOption
     cmdlet and the $PSSessionOption preference Variable.

    — You can also protect the remote computer by setting timeout values
     programmatically in the session configuration for the session.

    When a timeout value does not permit a operation to complete, Windows
    PowerShell terminates the operation and generates an error.

    To resolve the error, change the command to complete within the timeout
    interval or determine the source of the timeout limit and increase the
    timeout interval to allow the command to complete.

    For example, the following commans use the New-PSSessionOption cmdlet to
    create a session option object with an OperationTimeout value of 4 minutes
    (in MS) and then use the session option object to create a remote session.

        C:\PS> $pso = New-PSSessionoption -operationtimeout 240000

        C:\PS> New-PSSession -computername Server01 -sessionOption $pso

    For more information about the WS-Management timeouts, see the Help topic for
    the WS-Management provider (type “Get-Help WSMan“).

    For more information about the New-PSSsessionOption cmdlet, see
    New-PSSessionOption.

TROUBLESHOOTING UNRESPONSIVE BEHAVIOR

This section discusses remoting problems that prevent a command from completing
and prevent or delay the return of the Windows PowerShell prompt.

    HOW TO INTERRUPT A COMMAND
    ————————–
    Some native Windows programs, such as programs with a user interface, console
    applications that prompt for input, and console applications that use the
    Win32 console API, do not work correctly in the Windows PowerShell remote host.

    When you use these programs, you might see unexpected behavior, such as no
    output, partial output, or a remote command that does not complete.

    To end an unresponsive program, type CTRL + C. To view any errors that might
    have been reported, type “$error” in the local host and the remote session.

SEE ALSO
    Online version: http://go.microsoft.com/fwlink/?LinkID=135188
    about_remote
    about_remote_requirements

about_remote_requirements

TOPIC
    about_remote_requirements

SHORT DESCRIPTION
    Describes the system requirements and configuration requirements for
    running remote commands in Windows PowerShell.

LONG DESCRIPTION
    This topic describes the system requirements, user requirements, and
    resource requirements for establishing remote connections and running
    remote commands in Windows PowerShell. It also provides instructions for
    configuring remote operations.

    Note: Many cmdlets (including the Get-Service, Get-Process, Get-WmiObject,
         Get-EventLog, and Get-WinEvent cmdlets) get objects from remote
         computers by using Microsoft .NET Framework methods to retrieve the
         objects. They do not use the Windows PowerShell remoting
         infrastructure. The requirements in this document do not apply to
         these cmdlets.

         To find the cmdlets that have a ComputerName parameter but do not use
         Windows PowerShell remoting, read the description of the ComputerName
         parameter of the cmdlets.

SYSTEM REQUIREMENTS

    The local and remote computers must have:

        — Windows PowerShell 2.0 or later

        — The Microsoft .NET Framework 2.0 or later

        — Windows Remote Management 2.0

    To find the version number of an installed version of Windows PowerShell,
    use the $PSVersionTable automatic Variable. The value of the
    $PSVersionTable.Version.Major property must be at least 2.

    Windows Remote Management 2.0 is included in Windows 7 and in
    Windows Server 2008 R2. It is also included in the integrated installation
    package for earlier versions of Windows that includes Windows PowerShell.

    Windows PowerShell Integrated Scripting Environment (ISE) and the
    Out-GridView cmdlet require the Microsoft .NET Framework 3.5 with Service
    Pack 1. The Get-WinEvent cmdlet requires the Microsoft .NET Framework 3.5
    or greater. These upgrades are not required for remoting.

USER PERMISSIONS

    To establish a remote connection and run remote commands, the current user
    must be a member of the Administrators group on the remote computer. Or,
    the current user must be able to provide the credentials of an
    administrator.

RUN AS ADMINISTRATOR

    In Windows Vista, Windows Server 2008, and later versions of Windows,
    Administrator privileges are required for the following remoting
    operations:

        — Establishing a remote connection to the local computer. This is
         commonly known as a “loopback” scenario.

        — Managing session configurations on the local computer.

        — Viewing and changing WS-Management settings on the local computer.
         These are the settings in the LocalHost node of the WSMan: drive.

    To perform these tasks, you must start Windows PowerShell with the “Run
    as administrator” option even if you are a member of the Administrators
    group on the local computer.

    In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell
    with the “Run as administrator” option:

        1. Click Start, click All Programs, click Accessories, and then click
         the Windows PowerShell folder.

        2. Right-click Windows PowerShell, and then click
         “Run as administrator”.

    In Windows Vista and Windows Server 2008, to start Windows PowerShell with
    the “Run as administrator” option:

        1. Click Start, click All Programs, and then click the Windows
         PowerShell folder.

        2. Right-click Windows PowerShell, and then click
         “Run as administrator”.

    The “Run as administrator” option is also available in other Windows
    Explorer entries for Windows PowerShell, including shortcuts. Just
    right-click the item, and then click “Run as administrator”.

    When you start Windows PowerShell from another program such as Cmd.exe, use
    the “Run as administrator” option to start the program.

HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING

    The remoting features of Windows PowerShell are supported by the WinRM
    service, which is the Microsoft implementation of the Web Services for
    Management (WS-Management) protocol. To use the remoting features, you
    need to change the default configuration of WS-Management on the system.

    To configure Windows PowerShell to receive remote commands:

        1. Start Windows PowerShell. In Windows Vista and later versions of
         Windows, start Windows PowerShell with the “Run as administrator”
         option.

    2. At the command prompt, type:

     Enable-PSRemoting

    This procedure allows users on other computers to establish remote
    connections and to run remote commands on the local computer. It also
    allows you to create a “loopback” connection on the local computer.

    To verify that remoting is configured correctly, run a test command such as
    the following command, which creates a remote session on the local
    computer.

         New-PSSession

    If remoting is configured correctly, the command will create a session on
    the local computer and return an object that represents the session. The
    output should resemble the following sample output:

         C:\PS> New-PSSession

         Id Name        ComputerName    State    ConfigurationName
         — —-        ————    —–    —–
         1 Session1    localhost     Opened Microsoft.PowerShell

    If the command fails, see about_remote_TroubleShooting for assistance.

UNDERSTAND POLICIES

    When you work remotely, you use two instances of Windows PowerShell, one
    on the local computer and one on the remote computer. As a result, your
    work is affected by the Windows policies and the Windows PowerShell
    policies on the local and remote computers.

    In general, before you connect and as you are establishing the connection,
    the policies on the local computer are in effect. When you are using the
    connection, the policies on the remote computer are in effect.

SEE ALSO
    about_remote
    about_pssessions
    Invoke-Command
    Enter-PSSession
    New-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

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

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