Error executing Powershell commandlets using C#

Question:

I have the following code that I have tested and works:

However, when I try to include the function in a different project so that it is called from a webservice it throws an execption:

I have no idea why this is happening. Any help would be appreciated.

Answer:

What’s happening is that Impersonator only impersonates on the thread, and PowerShell’s Runspace is running on another thread.

To make this work, you need to add:

just before you open the runspace.

This will force the runspace to run on the same thread as the impersonated token.

Hope this helps,

Source:

Error executing Powershell commandlets using C# by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply