Programming4us
         
 
 
Sharepoint

SharePoint 2010 : Managing Systems Remotely with WinRM

12/10/2010 6:11:30 PM

Windows PowerShell 2.0 introduces a new capability to manage your systems remotely from your desktop by using either WinRM or Internet Information Server (IIS). WinRM is often the mechanism used by administrators and the subject of this section. Remote Management involves not just the ability to run Windows PowerShell locally on your machine using the few commands that allow you to specify a computer name as an optional parameter; it also includes methods known as fan-in and fan-out remoting and background jobs.

  • Fan-in remoting This allows many administrators to connect to an instance of Windows PowerShell running on the same remote servers—this is not supported out of the box in SharePoint 2010.

  • Fan-out remoting This allows you to send a single Windows PowerShell command to run multiple remote instances of Windows PowerShell in parallel, and the results of those commands will be returned to your desktop. You would use this if you need to complete the same task on multiple servers. You no longer need to establish a Remote Desktop connection to each server in turn and then execute the commands locally on that server. You can create a set of Windows PowerShell commands and pass the server names to those commands, which then completes the same commands sequentially for each server whose name you provide.

  • Background jobs Windows PowerShell 2.0 supports both local and remote background jobs. These are commands that execute asynchronously in the background with no interaction. When you execute a command in the background, the command prompt is returned immediately so that you can continue to execute other commands.

1. Configuring for WinRM

The WinRM Windows service must be started and configured for remoting on both your local computer and the server on which you want to remotely run commands. To find out if your server is running WinRM, type

Get-service winrm

To check if it is running on a remote server, type

Get-service winrm -computername $server_name

On your SharePoint server, this service should be running; however, if your local computer is running Windows 7 (or Windows Vista with Windows PowerShell 2.0 and WinRM 2.0 installed), you may need to start this service and enable remoting. You can do this by typing one command, Enable-PSRemoting, which executes two additional commands, Set-WSManQuickConfig and Start-Service WinRM.


Note:

If one of the network connection types is Public, the Set-WSManQuickConfig command will raise an Invalid Operation Exception. You will need to change the network connections to the network type of either Domain or Private to proceed.


The output to the Enable-PSRemoting command will look similar to the following example.

WinRM Quick Configuration
Running command "Set-WSManQuickConfig" to enable this machine for remote management
through WinRM service.
This includes:
1. Starting or restarting (if already started) the WinRM service
2. Setting the WinRM service type to auto start
3. Creating a listener to accept requests on any IP address
4. Enabling firewall exception for WS-Management traffic (for http only).
Do you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default
is "Y"): y
WinRM has been updated to receive requests.
WinRM service type changed successfully.
WinRM service started.
Configured LocalAccountTokenFilterPolicy to grant administrative rights remotely to
local users.
WinRM has been updated for remote management.
Created a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this
machine.
WinRM firewall exception enabled.

On a computer running a 64-bit version of Windows, you may see an additional confirmation message.
Are you sure you want to perform this action?
Performing operation "Registering session configuration" on Target "Session
configuration "Microsoft.PowerShell32" is not found. Running command
"Register-PSSessionConfiguration Microsoft.PowerShell32 -processorarchitecture x86
-force" to create "Microsoft.PowerShell32" session configuration. This will restart
WinRM service.".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is
"Y"):

To determine how WinRM is configured, the authentication method, and the port numbers it will access, use the following command.
winrm get winrm/config/service

This should result in an output similar to the following.

Service
RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GWGX;;;WD)
MaxConcurrentOperations = 4294967295
MaxConcurrentOperationsPerUser = 15
EnumerationTimeoutms = 60000
MaxConnections = 25
MaxPacketRetrievalTimeSeconds = 120
AllowUnencrypted = false
Auth
Basic = false
Kerberos = true
Negotiate = true
Certificate = false
CredSSP = false
CbtHardeningLevel = Relaxed
DefaultPorts
HTTP = 5985
HTTPS = 5986
IPv4Filter = *
IPv6Filter = *
EnableCompatibilityHttpListener = false
EnableCompatibilityHttpsListener = false
CertificateThumbprint

You can run winrm and winrm-related commands, such as the New-PSSession command, from either the Windows PowerShell console or the SharePoint 2010 Management Shell. However, these must be run as an administrator. To do this, right-click the Windows PowerShell console or the SharePoint 2010 Management Shell and then select Run As Administrator. You must be a member of the Administrators group on the remote machine or be able to provide administrator credentials to do this.

Note:

When your local computer and the remote computer are in different non-trusted domains or in a workgroup, additional steps are required to configure remoting. The workgroup scenario is likely to occur when SharePoint Foundation is installed for external collaboration or in a small business environment rather than in a typical SharePoint Server installation. For information on how to configure remoting between two workgroup machines, see the blog post at http://blogs.msdn.com/wmi/archive/2009/07/24/powershell-remoting-between-two-workgroup-machines.aspx.


2. Meeting Requirements for SharePoint PowerShell Remoting

To use WinRM to execute SharePoint PowerShell cmdlets on a remote machine, there are a number of additional requirements.

  1. You must have access to a userid with the correct rights to execute those commands. These requirements are applicable whether you are remoting into a server or locally executing SharePoint cmdlets. The userid must meet the following criteria.

    • Must be a member of the WSS_ADM_WGP local security group on the machine executing the commands.

    • Must be a member of the SharePoint_Shell_Access SQL Server role on the configuration database.

    • Must have access to the content database that you want to manipulate.

    You can use the SPShellAdmin cmdlets to help you manage these requirements. When you run the Add-SPShellAdmin cmdlet to add a userid to the SharePoint_Shell_Admin role, you must be mapped to Security_Admin role on the SQL instance and the db_owner role to the relevant databases. You need to run the Add-SPShellAdmin cmdlet for each content database that you want the userid to access.

  2. Designate one server in your farm as the server you will always use for remoting. On that server, increase the WinRM configuration option, MaxMemoryPerShellDB, to a large value, 512 or 1024. This configuration option limits the amount of memory a single remote process can use. Increasing the value will allow long-running commands to run without throwing OutOfMemory Exception errors. The command to display the values of the configuration options and sample output is shown here.

    winrm get winrm/config/winrs

    Winrs
    AllowRemoteShellAccess = true
    IdleTimeout = 180000
    MaxConcurrentUsers = 5
    MaxShellRunTime = 2147483647
    MaxProcessesPerShell = 15
    MaxMemoryPerShellMB = 150
    MaxShellsPerUser = 5

    To modify the MaxMemoryPerShellDB setting, type the following Windows PowerShell command in the SharePoint 2010 Management Shell.

    Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024

  3. You must use Credential Security Provider (CredSSP) authentication. This authentication mechanism, introduced with Windows Vista, allows an application to delegate the credentials from one machine to another, a process called double hopping. This will enable you to provide the credentials that allow the SharePoint PowerShell cmdlets to talk to the Microsoft SQL Server that is hosting your SharePoint databases. If you do not use CredSSP and you try to remotely execute a SharePoint cmdlet, you are likely to receive a message that indicates the farm is unavailable. In the output from the Winrm get winrm/config/service command shown previously, notice that CredSSP is equal to False. There are several ways you can modify WinRM configuration options, including Group Policy, login scripts, and the command prompt. To enable CredSSP authentication though command-line interfaces, complete the following tasks.

  1. On the computer from which you are remoting, such as your Windows 7 desktop, type the following command, where Web1 is the SharePoint server. Type Y when prompted to confirm that you want to enable CredSSP authentication.

    Enable-WSManCredSSP -role client -DelegateComputer Web1

  2. On the SharePoint server where you are remoting to, type

    Enable-WSManCredSSP -role server


Note:

MORE INFO For more information on multi-hop support in WinRM, see http://msdn.microsoft.com/en-us/library/ee309365(VS.85).aspx.


3. Using WinRM Remoting

The commands you need to start a remote session to remotely manage a SharePoint farm or one specific SharePoint server are similar to those in the following example.

$cred = Get-Credential contoso\spfarm
$sess = New-PSSession Web1 -Authentication CredSSP -Credential $cred
Invoke-Command -Session $sess -ScriptBlock `
{ADD-PSSnapin Microsoft.SharePoint.PowerShell;}


Note:

SECURITY ALERT You can limit the Windows PowerShell commands that a user can access during a remote session by using the –ConfigurationName parameter with the New-PSSession cmdlet or by using the Proxy cmdlet. For more information, see the blog post “Extending and/or Modifying Command with Proxies” at http://blogs.msdn.com/powershell/archive/2009/01/04/extending-and-or-modifing-commands-with-proxies.aspx.


When you enter the first command, a dialog box appears where you must type the password. This password and the user name are stored in the variable $Cred, which is used in the second command, New-PSSession, which establishes a persistent session with the remote server. Creating a persistent session is not necessary when using Windows PowerShell remoting, but if you do not establish a persistent connection, whenever you invoke a remote command that includes a SharePoint cmdlet, each Invoke-Command will also need to include the PSSnapin cmdlet. The third command, Invoke-Command PSSnapin, allows you to run SharePoint PowerShell cmdlets on the remote server.

Reference to the persistent session is stored in the variable $sess. You can direct any commands you want to that remote server by using this variable. In the following example, the cmdlet Get-SPServiceInstance is typed within the script block—the area between the curly brackets ({ }). The output from the Get-SPServiceInstance cmdlet returns the status of the services within a SharePoint farm.

Invoke-Command -Session $s -ScriptBlock {get-SPServiceInstance}


WARNING: column "PSComputerName" does not fit into the display and was removed.
TypeName Status Id
-------- ------ --
Business Data Connectivity Online 3ad4d004-9ae3-4810-94bf-76cc43c9d507
Microsoft SharePoint Foundati... Online 81cc6474-fd6f-42ad-a932-25d67cff8cc1
Microsoft SharePoint Foundati... Disabled cb3b976c-b451-4abe-b808-0c6d191ccd3d
Microsoft SharePoint Foundati... Online 5bac9c93-483a-4901-ae46-f6f7ae0a12a8
Central Administration Online 0c24457f-b58e-4daa-895e-4acd35ef7543
Microsoft SharePoint Foundati... Online 155570fa-0d4c-495d-9f31-5250e83bdd75
Microsoft SharePoint Foundati... Disabled c25ae170-c07d-48db-97b3-73b0d9b47e94
SharePoint Foundation Help Se... Online 8af8b8b1-92cb-48d2-8864-20a7e191d7c2



Note:

BEST PRACTICE You can type multiple commands in a script block, either on separate lines or on the same line separated by a semicolon (;). If only one command is entered in the script block, the semicolon is optional, but it is good practice to include it. You can also use local variables to generate a remote script block as in the following example.

$url = "http://contoso.com"
$myscript = "get-spsite $url"
$sb = [scriptblock]::Create($myscript)
Invoke-Command $sess -ScriptBlock $sb


You can use the Windows PowerShell Invoke-Command cmdlet to communicate with many sessions, either on the same server or on different servers, from your desktop. This cmdlet enables you to start multiple administrative tasks at the same time that are then run in parallel. However, if these tasks are long running, you will not get control back until the command on the remote machine finishes. This is known as running the command interactively. To run asynchronously as a background job so that the Windows PowerShell prompt returns immediately and you can enter other commands, append the –AsJob parameter to the Invoke-Command, or alternatively, use the Start-Job cmdlet. Using this technique can reduce the amount of time to complete your administrative tasks, compared to running them sequentially. An example of how this can save you a considerable amount of time is during the upgrade process, when each session runs a database-attach-upgrade, and the time taken to complete all database upgrades is limited only by the resources of your SQL Server.

If you have many short-running tasks to complete on a specific server and don’t want to keep typing Invoke-Command, use one of the following approaches.

  • You can enter an interactive session with that server by typing Enter-PSSession $sess. The command prompt will change from PS C:\Users\<userid>, where <userid> is the name of the current user, to [<remoteservername>]: PS C:\Users\<remotecredentials> \Documents, where <remotecredentials> is the userid you used for the CredSSP authentication. The command prompt reminds you that you are now submitting commands to the remote server. To return to interactive mode on your local computer, type Exit-PSSession or exit.

  • Use the Import-PSSession remoting cmdlet, also known as implicit remoting, to bring commands from the remote session into the local Windows PowerShell session. An additional advantage of the Import-PSSession approach is that you can interact with your local file system and talk to SharePoint as if you were logged on locally to the SharePoint server. By default, the Import-PSSession cmdlet imports all commands except commands that have the same name as commands in your current session. You can also import a subset of commands and prefix them with a word you specify, so that it is obvious to you which commands are local and which are remote. In the following example, the word Remote is added as a prefix to all SPSite cmdlets.

    Import-PSSession -session $sess -CommandName *-spsite -Prefix Remote


    ModuleType Name                      ExportedCommands
    ---------- ---- ----------------
    Script tmp_1833f7bc-b269-4229... {Set-SPSite, Backup-SPSite, Get-SPSite,...

    In this example, you can use all SPSite cmdlets as if they were local commands; for example, by typing Get-RemoteSPSite you can return all site collections that match the given criteria. These imported commands are stored in a temporary module that is deleted at the end of the session. To create a persistent module that you can use in future sessions, use the Export-PSSession cmdlet. The imported commands still run in the remote session from which they were imported and therefore may take longer to run than local commands.

When you have completed all of your tasks, you can delete the persistent connection between your local machine and the remote machine by typing Remove-PSSession $sess.



Other -----------------
- SharePoint 2010 : Installing Windows PowerShell
- SharePoint 2010 : Using Windows PowerShell: The Basics
- SharePoint 2010 : Modify a View
- SharePoint 2010 : Create Mobile Views
- Uninstalling SharePoint 2010
- Configuring a SharePoint 2010 Installation (part 1) - Renaming the Central Administration Database
- Configuring a SharePoint 2010 Installation (part 1) - Running the Farm Configuration Wizard
- SharePoint 2010 : Enable or Disable Inline Editing in a View
- Performing SharePoint 2010 Installations (part 5)
- Performing SharePoint 2010 Installations (part 4)
- Performing SharePoint 2010 Installations (part 3)
- Performing SharePoint 2010 Installations (part 2)
- Performing SharePoint 2010 Installations (part 1) - SharePoint 2010 Standalone Installation
- SharePoint 2010 : Specify the Item Limit for a View
- SharePoint 2010 : Specify How Folders Will Be Used in a View
- SharePoint 2010 : Specify a Different Item Style for a View
- SharePoint 2010 : Specify Totals for a View
- SharePoint 2010 : Specify How Items in a View Are Grouped
- SharePoint 2010 : Specify How Items in a View Are Filtered
- SharePoint 2010 : Specify How Items in a View Are Sorted
 
 
Most View
- Microsoft Dynamic AX 2009 : The Batch Framework (part 5) - Managing the Batch Server Execution Process - Set Up Server Configuration, Create a Batch Group
- Exchange Server 2010 : Availability Planning for Client Access Servers (part 4) - Creating a Client Access Server Array
- Windows Server 2008 : Installing the Web Server Role (part 1)
- Exchange Server 2010 : Troubleshooting Federated Delegation (part 1) - Troubleshooting the Federation Trust
- Windows Vista - File Encryption : Encryption File System
- Exchange Server 2007 : Modify Recipient Configuration Modify
- Windows 7 : Creating and Enforcing Bulletproof Passwords (part 2) - Taking Advantage of Windows 7’s Password Policies
- SharePoint 2010 : Content Management - Routing documents to another site
- Developing Applications for Windows Phone 7 : Data Binding (part 2)
- Windows Server 2008 : Configuring SMTP (part 2) - Creating a New SMTP Virtual Server
Top 10
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 3) - Configuring Recipient Filtering
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 2)
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 1)
- Implementing Edge Services for an Exchange Server 2007 Environment : Installing and Configuring the Edge Transport Server Components
- What's New in SharePoint 2013 (part 7) - BCS
- What's New in SharePoint 2013 (part 6) - SEARCH
- What's New in SharePoint 2013 (part 6) - WEB CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 5) - ENTERPRISE CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 4) - WORKFLOWS
- What's New in SharePoint 2013 (part 3) - REMOTE EVENTS