1

I have a powershell script that I would like to run from C#. The contents of the script are:

$w = Get-SPWebApplication "http://mysite/"
$w.UseClaimsAuthentication = 1
$w.Update()
$w.ProvisionGlobally()
$w.MigrateUsers($True) 

and is used to set a site to Claims Based Authentication. I know how to execute a multiple commands from C# but am not sure how to run the entire script taking into account the variable $w.

PowerShell OPowerShell = null;
Runspace OSPRunSpace = null;
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("Get-SPWebApplication");
Cmd1.Parameters.Add("http://mysite/");
OPowerShell.Commands.AddCommand(Cmd1);
// Another command
// Another command
OSPRunSpace.Open();
OPowerShell.Invoke();
OSPRunSpace.Close();

How would I execute all of the commands either by adding them as separate commands or saving the script to file and reading it in for execution? What is the best practice?

1 Answer 1

3

You can use the AddScript method to add a string containing a script:

OPowerShell.Commands.AddScript("@
 $w = Get-SPWebApplication ""http://mysite/""
 $w.UseClaimsAuthentication = 1
 $w.Update()
 $w.ProvisionGlobally()
 $w.MigrateUsers($True)
");

You can add multiple script excerpts to the pipeline before invoking it. You can also pass parameters to the script, like:

OPowerShell.Commands.AddScript("@
 $w = Get-SPWebApplication $args[0]
 ...
");
OPowerShell.Commands.AddParameter(null, "http://mysite/");

You can also have a look at Runspace Samples on MSDN.

--- Ferda

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.