gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:22:04 25 4
gpt4 key购买 nike

我有一个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();

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

最佳答案

您可以使用 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/");

您也可以看看 Runspace Samples on MSDN

-费尔达

关于c# - 从包含变量的C#执行多个Powershell命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10038685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com