gpt4 book ai didi

c# - 线程中的 powershell/runspace

转载 作者:行者123 更新时间:2023-12-01 14:44:25 26 4
gpt4 key购买 nike

我正在运行以下代码:

RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException warning;
config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out warning);
if (warning != null) throw warning;

Runspace thisRunspace = RunspaceFactory.CreateRunspace(config);
thisRunspace.Open();

string alias = usr.AD.CN.Replace(' ', '.');
string letter = usr.AD.CN.Substring(0, 1);
string email = alias + "@" + (!usr.Mdph ? Constantes.AD_DOMAIN : Constantes.MDPH_DOMAIN) + "." + Constantes.AD_LANG;
string db = "CN=IS-" + letter + ",CN=SG-" + letter + ",CN=InformationStore,CN=" + ((char)letter.ToCharArray()[0] < 'K' ? Constantes.EXC_SRVC : Constantes.EXC_SRVD) + Constantes.EXC_DBMEL;
string cmd = "Enable-Mailbox -Identity \"" + usr.AD.CN + "\" -Alias " + alias + " -PrimarySmtpAddress " + email + " -DisplayName \"" + usr.AD.CN + "\" -Database \"" + db + "\"";
Pipeline thisPipeline = thisRunspace.CreatePipeline(cmd);
thisPipeline.Invoke();

代码在以这种方式创建的线程中运行:

        t.WorkThread = new Thread(cu.CreerUser);
t.WorkThread.Start();

如果我直接运行代码(而不是通过线程),它就可以运行。

在线程中时,它抛出以下异常:ObjectDisposedException“安全句柄已关闭。” (译自法语)

然后我用“OpenAsync”替换了“Open”,这有助于没有得到之前的异常。但是在调用时,我得到以下异常:InvalidRunspaceStateException“无法调用管道,因为它的执行状态未打开。它的当前状态是打开。” (也译自法语)

我是无能的...

欢迎任何帮助!!!谢谢!!!


打开:

   à Microsoft.Win32.Win32Native.GetTokenInformation(SafeTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
à System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, UInt32& dwLength)
à System.Security.Principal.WindowsIdentity.get_User()
à System.Security.Principal.WindowsIdentity.GetName()
à System.Security.Principal.WindowsIdentity.get_Name()
à System.Management.Automation.MshLog.GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity)
à System.Management.Automation.MshLog.GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo)
à System.Management.Automation.MshLog.LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState, InvocationInfo invocationInfo)
à System.Management.Automation.MshLog.LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState)
à System.Management.Automation.Runspaces.LocalRunspace.OpenHelper()
à System.Management.Automation.Runspaces.RunspaceBase.CoreOpen(Boolean syncCall)
à System.Management.Automation.Runspaces.RunspaceBase.Open()
à Cg62.ComposantsCommuns.ActiveDirectory.Exchange.BoitesAuxLettres.CreationBAL(User usr, IList`1 log) dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\Exchange.cs:ligne 141
à Cg62.ComposantsCommuns.ActiveDirectory.ComptesUtilisateurs.CreationUser.CreerUser() dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\ComptesUtilisateurs.cs:ligne 199
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.runTryCode(Object userData)
à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()

使用 OpenAsync:

   à System.Management.Automation.Runspaces.RunspaceBase.AddToRunningPipelineList(PipelineBase pipeline)
à System.Management.Automation.Runspaces.RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(PipelineBase pipeline, Boolean syncCall)
à System.Management.Automation.Runspaces.PipelineBase.CoreInvoke(IEnumerable input, Boolean syncCall)
à System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
à System.Management.Automation.Runspaces.Pipeline.Invoke()
à Cg62.ComposantsCommuns.ActiveDirectory.Exchange.BoitesAuxLettres.CreationBAL(User usr, IList`1 log) dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\Exchange.cs:ligne 149
à Cg62.ComposantsCommuns.ActiveDirectory.ComptesUtilisateurs.CreationUser.CreerUser() dans D:\Applications\Commun\Sources .Net\COMIAD\COMIAD\ComptesUtilisateurs.cs:ligne 199
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.runTryCode(Object userData)
à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()

抱歉回复晚了...我有很多事要做


已升级到 Powershell 2.0,我已通过打开错误但现在我在 Invoke 上有以下内容。我将命令更改为:

Enable-Mailbox -Identity "Aagtest Abe" -Alias Aagtest.Abe -PrimarySmtpAddress smtp.address@domain.com -DisplayName "Aagtest Abe" -Database "myDb" -DomainController adc.domain.int

该命令在 powershell 中运行良好。我收到以下异常 CmdletInvocationException :“唯一异常(exception)是 été levée par l'initialiseur de type pour ' '。”不知道如何翻译...

堆栈跟踪:

   à Microsoft.Exchange.Data.Directory.DSAccessTopologyProvider..ctor(String machineName)
à Microsoft.Exchange.Data.Directory.DSAccessTopologyProvider..ctor()
à Microsoft.Exchange.Data.Directory.DirectoryServicesTopologyProvider.DiscoverConfigDC()
à Microsoft.Exchange.Data.Directory.DirectoryServicesTopologyProvider..ctor()
à Microsoft.Exchange.Data.Directory.TopologyProvider.InitializeInstance()
à Microsoft.Exchange.Data.Directory.TopologyProvider.GetInstance()
à Microsoft.Exchange.Data.Directory.ADSession.GetConnection(String preferredServer, Boolean isWriteOperation, Boolean isNotifyOperation, ADObjectId& rootId)
à Microsoft.Exchange.Data.Directory.ADSession.GetReadConnection(String preferredServer, ADObjectId& rootId)
à Microsoft.Exchange.Data.Directory.ADSession.IsReadConnectionAvailable()
à Microsoft.Exchange.Configuration.Tasks.RecipientObjectActionTask`2.InternalBeginProcessing()
à Microsoft.Exchange.Management.RecipientTasks.EnableMailbox.InternalBeginProcessing()
à Microsoft.Exchange.Configuration.Tasks.Task.BeginProcessing()
à System.Management.Automation.Cmdlet.DoBeginProcessing()
à System.Management.Automation.CommandProcessorBase.DoBegin()

最佳答案

因此,该问题的最终答案是,如果您通过 advapi32 LogonUser 进行模拟,则无法执行远程 Exchange powershell 命令。

根据我的测试,命令是否在线程中执行根本无关紧要。

似乎正确的方法 - 对我有用的方法 - 是在连接到 Runspace 后立即进行身份验证。

至于为什么会这样……尽管告诉我!!

此代码不得在模拟时执行。

        IContexteRemotePowerShell crp:
crp.ConfigurationName = "Microsoft.Exchange";
crp.RemoteUri = "http://exhangeserver/powershell";
crp.User = "account who has rights to do stuff on the exchange server";
crp.Password = "its password";
crp.Domaine = "Domain";


private static void Connect(IContexteRemotePowerShell contexte)
{
try
{
Espace = RunspaceFactory.CreateRunspace();
Espace.Open();
}
catch (InvalidRunspaceStateException ex)
{
throw new TechniqueException(MethodBase.GetCurrentMethod(), "Error while creating runspace.", ex);
}

// Create secure password
SecureString password = new SecureString();
foreach (char c in contexte.Password)
{
password.AppendChar(c);
}

// Create credential
PSCredential psc = new PSCredential(contexte.User, password);

PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("Credential", psc);

if (!String.IsNullOrEmpty(contexte.Serveur))
command.AddParameter("computername", contexte.Serveur);
if (!String.IsNullOrEmpty(contexte.RemoteUri))
command.AddParameter("ConnectionUri", new Uri(contexte.RemoteUri));
if (!string.IsNullOrEmpty(contexte.ConfigurationName))
command.AddParameter("ConfigurationName", contexte.ConfigurationName);

//// Create the session
PowerShell powershell = PowerShell.Create();
powershell.Commands = command;
powershell.Runspace = Espace;
Collection<PSObject> result = ExecuterCommande(command);

if (result.Count != 1)
throw new TechniqueException(MethodBase.GetCurrentMethod(),
"Error while connecting.");

// Create session variable
command = new PSCommand();
command.AddCommand("Set-Variable");
command.AddParameter("Name", "ra");
command.AddParameter("Value", result[0]);
ExecuterCommande(command);
}

private const string InvokeCommand = "Invoke-Command -ScriptBlock {{ {0} }} -Session $ra";

private static string ExecuteRemoteScript(string cmd)
{
PSCommand command = new PSCommand();
command.AddScript(string.Format(InvokeCommand, cmd));
Collection<PSObject> result = ExecuterCommande(command);

StringBuilder sb = new StringBuilder();
foreach (PSObject obj in result)
{
sb.AppendLine(obj.ToString());
}
return sb.ToString().Trim();
}

关于c# - 线程中的 powershell/runspace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1013331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com