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);
}
}
它不喜歡'runspace.ApartmentState =系統。 Threading.ApartmentState.STA',因爲當前線程不是STA線程。你需要刪除這一行或刪除它上面的行... – 2013-05-08 05:30:52
如果我刪除任一行,它會引發錯誤「指定方法不受支持」 – user2360891 2013-05-08 05:39:08
它說不支持哪種方法? – 2013-05-08 05:39:56