One of the great innovations in Windows PowerShell is the ability to host the PowerShell run-time environment in any number of run-time hosts. We use this capability to host PowerShell in an ASP.NET web application process for our PeopleProvision solution. Everything works great once you get over a couple of big security hurdles.
- File SomePowerShellFile.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.
- Access to the registry key ‘HKEY_LOCAL_MACHINESOFTWAREMicrosoftPowerShell1ShellIdsMicrosoft.PowerShell’ is denied.
Many sources on the web document exactly what is going on with these error messages. Basically, Microsoft architected PowerShell and Windows Server 2008 R2 so the operating environment is protected from unauthorized PowerShell script execution. This is a good thing. However, it’s not so good when you need to run your own PowerShell script in a host other than the standard PowerShell command shell. You can’t just right-click and choose Run as administrator when your PowerShell host environment doesn’t have a GUI. In a scenario where you host PowerShell in an ASP.NET process, how do you get around this?
It turns out that you can securely run scripts on your system by changing the PowerShell execution policy. In your script, include a command to set the execution policy to an acceptable level for your needs. For example, the command below allows local scripts and signed scripts from the Internet (RemoteSigned policy) to run only in the current PowerShell process (Process scope). This is a great way to run your trusted scripts in an ASP.NET process without opening up tons of security holes.[sourcecode language=”powershell”]Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned[/sourcecode]
After you add this to your script, save the script and then try to run your ASP.NET application. If you see the following error then you might need to restart IIS (or at least unload the application pool by stopping and starting the web site) to get your changes to take effect.
Access to the registry key 'HKEY_LOCAL_MACHINESOFTWAREMicrosoftPowerShell1ShellIdsMicrosoft.PowerShell' is denied.
That should be all you need to safely execute your PowerShell scripts from an IIS application pool. Check out the PowerShell Set-ExecutionPolicy cmdlet documentation for more options to set the appropriate PowerShell execution policy for your needs.