简体   繁体   English

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

[英]Execute multiple Powershell commands from C# containing variable

I have a powershell script that I would like to run from C#. The contents of the script are:我有一个 powershell 脚本,我想从 C# 运行它。脚本的内容是:

$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.我知道如何从 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();

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?最佳做法是什么?

You can use the AddScript method to add a string containing a script:您可以使用AddScript方法添加包含脚本的字符串:

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 .您还可以查看MSDN 上的 Runspace Samples

--- Ferda ---费尔达

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM