从C#MVC Web应用程序执行PowerShell脚本
我需要从asp.net MVC Web应用程序执行powershell脚本。我的要求是动态创建网站集。我有它的脚本,它工作得很好。没有参数要传递给脚本。我一直使用的代码如下所示:从C#MVC Web应用程序执行PowerShell脚本,c#,asp.net-mvc,powershell,scripting,C#,Asp.net Mvc,Powershell,Scripting,我需要从asp.net MVC Web应用程序执行powershell脚本。我的要求是动态创建网站集。我有它的脚本,它工作得很好。没有参数要传递给脚本。我一直使用的代码如下所示: RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspa
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfiellocation);
pipeline.Commands.Add(myCommand);
pipeline.Commands.Add("Out-String");
// Execute PowerShell script
var result = pipeline.Invoke();
在执行代码时,当我检查变量result的计数时,它给出的计数为1。但是,在检查我的网站时,没有创建网站集。我无法确定哪里出了问题,因为没有运行时错误,Invoke命令似乎也正常运行
有人能告诉我我可能要去哪里吗?考虑到PowerShell脚本在运行管理shell时可以完美地工作。我不知道它是否有帮助,但我从不使用管道来运行命令shell,我不确定它是如何工作的 但这里有一个简单的例子
Runspace RS = RunspaceFactory.CreateRunspace(myConnection);
PowerShell PS = PowerShell.Create();
PSCommand PScmd = new PSCommand();
string cmdStr = "Enable-Mailbox -Identity " + username + " -Database DB01 -Alias " + aliasexample;
PScmd.AddScript(cmdStr);
try
{
RS.Open();
PS.Runspace = RS;
PS.Commands = PScmd;
PS.Invoke();
}
catch (Exception ex)
{
ex.ToString();
}
finally
{
RS.Dispose();
RS = null;
PS.Dispose();
PS = null;
}
使用try-catch,如果出现问题,您可以通过调试捕获错误。
如果我没记错的话,我必须把ACL.exe放在文件系统的权限中,这样我就可以执行命令shell,你可以在谷歌上快速搜索它。
希望这能有所帮助。我不得不放弃管道方法,因为我无法找出问题所在。该方法的另一个问题是抛出了错误:“Get-SPWbTemplate未被识别为cmdlet”。以下代码对我来说工作得非常好,并创建了所需的网站集:
PowerShell powershell = PowerShell.Create();
//RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
//Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration)
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
//RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
//scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
powershell.Runspace = runspace;
//powershell.Commands.AddScript("Add-PsSnapin Microsoft.SharePoint.PowerShell");
System.IO.StreamReader sr = new System.IO.StreamReader(scriptfilepath);
powershell.AddScript(sr.ReadToEnd());
//powershell.AddCommand("Out-String");
var results = powershell.Invoke();
if (powershell.Streams.Error.Count > 0)
{
// error records were written to the error stream.
// do something with the items found.
}
}
此外,不需要设置执行策略。可能是权限问题。运行站点的帐户是否具有所需的权限?检查调用操作后管道的状态。操作结束后,管道状态显示为已完成。是的,该帐户也具有所需的权限。你知道还有什么可能导致这个问题吗?我确实使用了try-catch块。但它从未进入挡块。因此,我无法找出哪里出了问题!!!就像我说的,我不知道如何使用管道,所以我不能告诉你,但是通过检查这个类,你可能会做这个var error=Pipeline.error.Read()作为集合,然后验证其是否为null,然后对其进行迭代以检查错误,如果不是,则可能与权限有关,或者您的系统中缺少某些文件(如我),我在主机上使用Acl来运行powershell命令权限。在web应用程序中执行命令shell可能很棘手。