我有C#Asp.Net的應用程序,連接到遠程計算機(遠程相對於Web服務器)運行使用PowerShell對他們的命令。 這通常工作,但在某些情況下(我不完全理解還),我們完全失去建立任何遠程會話能力。當發生這種情況,任何試圖連接到遠程的PowerShell導致以下異常:PowerShell遠程:在WSManClientSessionTransportManager.Initialize例外PSInvalidOperationException()
System.Management.Automation.PSInvalidOperationException
at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager.Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo)
at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager..ctor(Guid runspacePoolInstanceId, WSManConnectionInfo connectionInfo, PSRemotingCryptoHelper cryptoHelper, String sessionName)
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl..ctor(ClientRemoteSession session, PSRemotingCryptoHelper cryptoHelper, RunspaceConnectionInfo connectionInfo, URIDirectionReported uriRedirectionHandler)
at System.Management.Automation.Remoting.ClientRemoteSessionImpl..ctor(RemoteRunspacePoolInternal rsPool, URIDirectionReported uriRedirectionHandler)
at System.Management.Automation.Internal.ClientRunspacePoolDataStructureHandler..ctor(RemoteRunspacePoolInternal clientRunspacePool, TypeTable typeTable)
at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal.CreateDSHandler(TypeTable typeTable)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspacePool(Int32 minRunspaces, Int32 maxRunspaces, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments)
at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspacePool(Int32 minRunspaces, Int32 maxRunspaces, RunspaceConnectionInfo connectionInfo)
...
當該條件開始,這個異常被拋出的所有嘗試連接到任何主機,並從我可以告訴,這在發起主機上完全是客戶端問題。
我還沒有發現任何解釋的是,這裏或MS論壇。這是而不是與任何種類的用戶權限的問題,因爲一切工作,直到某些條件在Microsoft組件內被觸發。
這是我如何連接:
WSManConnectionInfo ci = new WSManConnectionInfo(
false, host, 5985, "/wsman",
"http://schemas.microsoft.com/powershell/Microsoft.PowerShell",
credential
);
ci.AuthenticationMechanism = AuthenticationMechanism.Credssp;
我試圖獲得運行空間直接:
runspace = RunspaceFactory.CreateRunspace(ci);
runspace.ApartmentState = ApartmentState.MTA; // other values don't help
runspace.Open();
,並通過池:
pool = RunspaceFactory.CreateRunspacePool(1, 5, ci);
pool.ApartmentState = ApartmentState.MTA;
pool.Open();
...這使得沒有區別,只有少數外層堆疊框架略有不同。
我懷疑這是與線程。我們直接從IIS線程響應AJAX請求(同步)執行一些PowerShell連接,並且一些連接是通過ThreadPool.QueueUserWorkItem(...)
以異步方式從單獨的線程完成的。 因此,在開始時(重新啓動IIS時),兩種類型的調用都起作用,然後在某些不良事件發生後,所有類型的連接嘗試都會引發上述異常。這始終發生在同步調用所做的事情之後(這非常簡單,看似良性),並且從來沒有在異步調用之後發生。 IIS重新啓動清除,直到條件再次觸發。
看起來好像有些PowerShell操作可能無法正確釋放資源。會話完成後,我嘗試在運行空間/池上使用Close()
,Disconnect()
和Dispose()
的所有組合關閉它們,但沒有任何區別。
PS。有此事件日誌中的遠程管理:
(Event ID: 28) Access Denied error: the WSManCreateSession API caller does not match the creator of the application object
此信息首次出現後成功同步PowerShell的連接,然後在此後的所有連接。