Running remote Powershell scripts for SharePoint   

Technorati Tags:


I’ve been playing around with Powershell the last week and thought I’d post some of my trickier findings:


Remoting with powershell


With remoting you can script installations or configurations that should be done on multiple farms/servers without having to login to each farm and run the script with it’s variables. Now you can just build 1 big script with variables and run each part of the script with a remote powershell session opened with the correct credentials.


The code below calls some functions to start a new remote session with fixed name, load variable / functions file into the session to be used later, run your code using the variables and functions, end session.


StartRemoting $AUTH_Servername $AUTH_ServerUser $AUTH_ServerUserPassword
            $s = Get-PSSession -Name "RemoteSP2010Script"
            Invoke-Command -Session $s -ScriptBlock {
                                                #YOUR CODE
            StopRemoting $AUTH_Servername


function LoadSharePointCmdlets()

Write-Host "- Loading SharePoint cmdlets" -foregroundcolor "Green"
Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function StartRemoting($Server, $Username, $Password)
    #Build credentials from variables
    if($Username -eq $NULL)
        $Credentials = $NULL
        $Credentials = New-Object -TypeName System.Management.Automation.PSCredential 
                                                        -argumentlist $Username , $Password 

    #enable remoting
    enable-PSRemoting -confirm:$false
    #increase memory limit for remote shell
    Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1000 

    #Disconnects the client remote desktop
    #Enable-WSManCredSSP -Role client -DelegateComputer $Server -Force
    Write-Host "Starting new remote session to" $Server -foregroundcolor "Green"
       if ($Credentials -eq $NULL)  
            $s = new-psSession -ComputerName $Server -Name "RemoteSP2010Script"
           $s = new-psSession -ComputerName $Server -Authentication CredSSP
                                       –Credential $Credentials -Name "RemoteSP2010Script"
    #Load Variables & functions into remote session
    Write-Host "Loading variables and functions into remote session"  -foregroundcolor "Green"
    Invoke-Command -Session $s -FilePath $VariableFileLocation -ErrorAction SilentlyContinue
    Invoke-Command -Session $s -FilePath $FunctionsFileLocation -ErrorAction SilentlyContinue

function StopRemoting($Server)
    Write-Host "Closing remote session to" $Server -foregroundcolor "Green"
    Remove-PSSession -ComputerName $Server
Posted by  Van Rousselt Tom  on  10/12/2011
0  Comments  |  Trackback Url  | 0  Links to this post | Bookmark this post with:        

Links to this post