2011-07-04 64 views
4

執行PowerShell的命令行開關我有下面的代碼,我已經測試和工程:錯誤使用C#

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(); 
    } 

然而,當我嘗試包括在不同的項目中的功能,使其從一個web服務稱它爲拋出一個錯誤:

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. 

我不知道爲什麼會發生這種情況。任何幫助,將不勝感激。

+0

什麼是你與假冒者對象執行計劃創建運行空間?由於此刻你似乎沒有使用它... –

+0

這是我的嘗試來解決這個問題。它被公佈爲類似問題的解決方案。 – firthh

回答

7

發生了什麼是Impersonator只模仿線程,並且PowerShell的運行空間在另一個線程上運行。

爲了使這項工作,你需要添加:

runspace.ApartmentState = System.Threading.ApartmentState.STA; 
runspace.ThreadOptions = System.Management.Automation.Runspaces.PSThreadOptions.UseCurrentThread; 

打開運行空間之前。

這將強制運行空間在與模擬令牌相同的線程上運行。

希望這有助於

+1

我認爲你的意思是「UseCurrentThread」而不是「ReuseThread」。 – x0n

+0

的確我是。我確定了答案。 –

+0

是的。這解決了我的問題。謝謝。 – firthh

1

使用這些命名空間:

using System.Management.Automation; 
using System.Management.Automation.Runspaces; 
using System.Threading; 

與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(); 
}