![](/img/trans.png)
[英]Execute Powershell containing Sharepoint commands on remote server, from C#
[英]Execute multiple Powershell commands from C# containing variable
我有一個 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/");
您還可以查看MSDN 上的 Runspace Samples 。
---費爾達
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.