我正在尝试在远程服务器中调用powershell脚本文件,该文件基本上获取参数并使用该参数创建共享驱动器。凭据都是正确的但每当我运行它时,它都会返回此错误:
当运行空间设置为使用当前线程时,调用设置中的单元状态必须与当前线程的单元状态相匹配
这与凭证有关,因为一旦我删除了凭证,它就可以在我的本地机器上正常运行。 任何人都可以阐明这一点吗?谢谢,
以下是我的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 :(得分:0)
我认为你使用了错误的构造函数重载WSManConnectionInfo。您可以在创建对象后检查对象的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