当我尝试在我的SharePoint解决方案中运行power-shell脚本时,我遇到了以下错误
的类型初始值设定项 'System.Management.Automation.SessionStateScope'引发了异常。
只是一个参考
private void RunPowershellScript(string scriptFile, List<string> parameters)
{
PowerShell OPowerShell = null;
Runspace OSPRunSpace = null;
try
{
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("backup-spsite");
Cmd1.Parameters.Add("identity", "Your Site Coll URL");
Cmd1.Parameters.Add("path", "Back up file path");
OPowerShell.Commands.AddCommand(Cmd1 );
OSPRunSpace.Open();
OPowerShell.Invoke();
OSPRunSpace.Close();
}
catch (Exception Ex)
{
//Handle exception
}
finally
{
if (OSPRunSpace != null)
{
OSPRunSpace.Dispose();
OSPRunSpace = null;
}
if (OPowerShell != null)
{
OPowerShell.Dispose();
OPowerShell = null;
}
}