1

我有一个我想从 C# 运行的 powershell 脚本。脚本的内容是:

$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();

我将如何通过将它们添加为单独的命令或将脚本保存到文件并将其读取以执行来执行所有命令?最佳做法是什么?

4

1 回答 1

3

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

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/");

您还可以查看MSDN 上的 Runspace Samples

--- 费尔达

于 2012-04-06T07:19:29.530 回答