Reputation: 9777
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?
Upvotes: 1
Views: 2733
Reputation: 5709
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
Upvotes: 3