Executing PowerShell command in web method of a web service hosted on SharePoint 2013 farm

This post is a contribution from Pavan Kumar, an engineer with the SharePoint Developer Support team

I worked on a very interesting case where I had to execute powershell commands in web method of a web service. But while executing powershell command I get following error

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

When I try the same on Sharepoint 2010 it works fine but this fails only on Sharepoint 2013 environments

After a lot of digging I could find the resolution

In the web.config of my web application I changed the legacyCasModel to "false" in the below tag

<trust level="Full" originUrl="" legacyCasModel="true" />

To know more about “legacyCasModel” refer to this article