2013-05-08 51 views
1

我想調用基本上獲取參數的遠程服務器中的powershell腳本文件,並使用該參數創建共享驅動器。憑據是正確的,但每當我運行此,它返回此錯誤:在C#中調用具有不同憑據的遠程PowerShell腳本

When the runspace is set to use the current thread the apartment state in the invocation settings must match that of the current thread

這是值得做的憑證,因爲一旦我刪除了證書,它運行在我的本地機器上的罰款。 任何人都可以闡明這一點嗎?謝謝,

下面是我的C#腳本:

PSCredential credential = new PSCredential(_exchangeUsername, password); 

// Set exchange connection details 
WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(_exchangeConnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential); 

connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default; 
string cmdArg = @"\\servername\\c$\\scripts\\HomeDrive.ps1 "+userID; 

using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) 
{ 
    try 
    { 
     runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; 
     runspace.ApartmentState = System.Threading.ApartmentState.STA; 
     runspace.Open(); 

     Pipeline pipeline = runspace.CreatePipeline(); 
     pipeline.Commands.AddScript(cmdArg); 
     pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); 
     Collection<PSObject> results = pipeline.Invoke(); 
     var error = pipeline.Error.ReadToEnd(); 
     // Check for powershell command errors 
     if (error.Count > 0) 
     { 
      throw new Exception(errorMessage.ToString()); 
     } 

     // Check for powershell command results 
     if (results.Count <= 0) 
     { 
      throw new Exception(String.Format("Error. No results after command invoked.", userID)); 
     } 
     runspace.Close(); 
    } 
    catch (Exception ex) 
    { 
     runspace.Close(); 
     throw new ApplicationException(String.Format("Error ", userID), ex); 
    } 
} 
+0

它不喜歡'runspace.ApartmentState =系統。 Threading.ApartmentState.STA',因爲當前線程不是STA線程。你需要刪除這一行或刪除它上面的行... – 2013-05-08 05:30:52

+0

如果我刪除任一行,它會引發錯誤「指定方法不受支持」 – user2360891 2013-05-08 05:39:08

+0

它說不支持哪種方法? – 2013-05-08 05:39:56

回答

0

我想你使用了錯誤的構造函數重載WSManConnectionInfo。您可以在創建對象後檢查對象的Credential屬性,但在傳遞它以創建運行空間之前,請檢查該對象的Credential屬性。

下面是從我自己的代碼片段,其中該工作正常,在我使用的最詳細的構造函數(我認爲)

#region create WSmanconnection 
//Create the PowerShell Remoting WinRM WSMan connection object so we can connect to the remote machine, only using credentials if Not Implicitly negotiated. 
var ci = new WSManConnectionInfo(
    useSSL, trueFQDN , port, appName, shellUri, 
    (authenticationMechanism == AuthenticationMechanism.NegotiateWithImplicitCredential) ? null : credential) 
    { 
     AuthenticationMechanism = authenticationMechanism, 
     OpenTimeout = openTimeoutMinutes * 60 * 1000, 
     OperationTimeout = operationTimeoutMinutes * 60 * 1000, 
     IdleTimeout = idleTimeOut * 60 * 1000 
    }; 
#endregion 
相關問題