从包含变量的C#执行多个Powershell命令

从包含变量的C#执行多个Powershell命令,c#,sharepoint,powershell,sharepoint-2010,C#,Sharepoint,Powershell,Sharepoint 2010,我有一个powershell脚本,我想从C#运行它。脚本的内容包括: $w = Get-SPWebApplication "http://mysite/" $w.UseClaimsAuthentication = 1 $w.Update() $w.ProvisionGlobally() $w.MigrateUsers($True) 用于将站点设置为基于声明的身份验证。我知道如何从C#执行多个命令,但考虑到变量$w,我不确定如何运行整个脚本 PowerShell OPowerShell = n

我有一个powershell脚本,我想从C#运行它。脚本的内容包括:

$w = Get-SPWebApplication "http://mysite/"
$w.UseClaimsAuthentication = 1
$w.Update()
$w.ProvisionGlobally()
$w.MigrateUsers($True) 
用于将站点设置为基于声明的身份验证。我知道如何从C#执行多个命令,但考虑到变量$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();
我如何执行所有命令,或者将它们作为单独的命令添加,或者将脚本保存到文件中并读入执行?最佳做法是什么?

您可以使用该方法添加包含脚本的字符串:

OPowerShell.Commands.AddScript("@
 $w = Get-SPWebApplication ""http://mysite/""
 $w.UseClaimsAuthentication = 1
 $w.Update()
 $w.ProvisionGlobally()
 $w.MigrateUsers($True)
");
在调用管道之前,可以将多个脚本摘录添加到管道中。您还可以向脚本传递参数,如:

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

---费达