Error executing Powershell commandlets using C#
I have the following code that I have tested and works:
using (new Impersonator("Administrator", "dev.dev", #########"))
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();
Command myCmd = new Command(@"C:\test.ps1");
myCmd.Parameters.Add(new CommandParameter("upn", upn));
myCmd.Parameters.Add(new CommandParameter("sipAddress", sipAddress));
pipeline.Commands.Add(myCmd);
// Execute PowerShell script
Collection<PSObject> results = pipeline.Invoke();
}
However, when I try to include the function in a different project so that it is called from a webservice it throws an execption:
System.Management.Automation.CmdletInvocationException: Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. ---> System.UnauthorizedAccessException: Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
I have no开发者_JAVA百科 idea why this is happening. Any help would be appreciated.
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:
runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.ThreadOptions = System.Management.Automation.Runspaces.PSThreadOptions.UseCurrentThread;
just before you open the runspace.
This will force the runspace to run on the same thread as the impersonated token.
Hope this helps,
Use these namespaces :
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
Create Runspace with InitialSessionState
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ApartmentState = ApartmentState.STA;
initialSessionState.ThreadOptions = PSThreadOptions.UseCurrentThread;
using ( Runspace runspace = RunspaceFactory.CreateRunspace ( initialSessionState ) )
{
runspace.Open();
// scripts invocation
runspace.Close();
}
精彩评论