0

i am getting below error while i am trying to run power-shell script in my SharePoint solution

The type initializer for 'System.Management.Automation.SessionStateScope' threw an exception.

just a reference

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;
        }
    }
4
  • can you add some code? Commented Mar 16, 2016 at 8:39
  • Can you check what the inner exception is please it might give a further explanation as to why Commented Mar 16, 2016 at 9:42
  • in the web.config file change the legacyCasModel to "false" in the below tag <trust level="Full" originUrl="" legacyCasModel="true" /> Commented Mar 16, 2016 at 9:45
  • can you please give me a sample so i can refer that because right now i dont have any web.config file in my solution Commented Mar 16, 2016 at 12:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.