Posts Tagged ‘Powershell’

Execute SharePoint Power shell commands from C# code

July 25, 2010

A friend of mine asked me yesterday how can we run a SharePoint power shell command like backup a site collection from a C# windows application and i decided to give it a try and here are the steps on how can we do it.

1. Add a reference to “System.Management.Automation” assembly in your project. I could not locate the assembly and a bit goggling suggested that add the following xml to your csproj file by editing it directly.

<Reference Include="System.Management.Automation" />

2. Add a using statement for following namespace:

using System.Management.Automation

3. Call following method on your button click event. This method executes “backup-spsite” command to backup a site collection. Modify the method by changing your site collection URL and backup file path and you are good to go.

  private void ExecutePowerShell()
        {
            PowerShell OPowerShell = null;
            Runspace OSPRunSpace = null;

            try
            {
                RunspaceConfiguration OSPRSConfiguration = RunspaceConfiguration.Create();
                PSSnapInException OExSnapIn = null;

                //Add a snap in for SharePoint. This will include all the power shell commands for SharePoint
                PSSnapInInfo OSnapInInfo = OSPRSConfiguration.AddPSSnapIn(“Microsoft.SharePoint.PowerShell”, out OExSnapIn);

                OSPRunSpace = RunspaceFactory.CreateRunspace(OSPRSConfiguration);

                OPowerShell = PowerShell.Create();

                OPowerShell.Runspace = OSPRunSpace;

                Command Cmd1 = new Command(“backup-spsite”);
                Cmd1.Parameters.Add(“identity”, “Your Site Coll URL”);
                Cmd1.Parameters.Add(“path”, “Back up file path”);

                OPowerShell.Commands.AddCommand(Cmd1);

                OSPRunSpace.Open();

                OPowerShell.Invoke();

                OSPRunSpace.Close();
            }
            catch (Exception Ex)
            {
                //Handle exception
            }
            finally
            {
                if (OSPRunSpace != null)
                {
                    OSPRunSpace.Dispose();
                    OSPRunSpace = null;
                }

                if (OPowerShell != null)
                {
                    OPowerShell.Dispose();
                    OPowerShell = null;
                }
            }
        }

Power shell is a wide subject and there are many things which you can do like executing the commands on remote machine, writing your own commands etc. I’ll write down about these in my future posts.