我正在尝试在远程服务器中调用一个 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);
}
}