2013-05-13 44 views
2

我想從C#中使用Enter-PSsession來啓用和使用Powershell遠程處理來遠程運行命令。 這是一個代碼從C#使用Enter-PSsession的Powershell v3遠程處理

Runspace remoteRunspace = Runspaces.RunspaceFactory.CreateRunspace(); 
remoteRunspace.Open(); 
powershell.Runspace = remoteRunspace; 
PSCommand command = new PSCommand(); 
command.AddCommand("Enter-PSSession"); 
command.AddParameter("ComputerName", "remotehostname"); 
command.AddParameter("Credential", vmmCredential); 
powershell.Commands = command; 
powershell.Invoke(); 

我得到CmdletInvocationException。 以下是相同的細節。

System.Management.Automation.CmdletInvocationException未處理 Message =該方法或操作未實現。 源= System.Management.Automation WasThrownFromThrowStatement =假 堆棧跟蹤: 在> System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(對象輸入,哈希表errorResults,布爾歷數) 在System.Management.Automation.Internal.PipelineProcessor .SynchronousExecute(Array input,Hashtable errorResults) at System.Management.Automation.Internal.PipelineProcessor.Execute(Array input) at System.Management.Automation.Internal.PipelineProcessor.Execute() at System.Management.Automation.Runspaces .LocalPipeline.InvokeHelper() at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc() InnerException:System.Manage ment.Automation.PSNotImplementedException Message =方法或操作未實現。 源= System.Management.Automation 堆棧跟蹤: 在> System.Management.Automation.Internal.Host.InternalHost.GetIHostSupportsInteractiveSession() 在> System.Management.Automation.Internal.Host.InternalHost.PushRunspace(運行空間運行空間) 在Microsoft.PowerShell.Commands.EnterPSSessionCommand.ProcessRecord() 在System.Management.Automation.Cmdlet.DoProcessRecord() 在System.Management.Automation.CommandProcessor.ProcessRecord() 的InnerException:

如果我嘗試直接從PowerShell的Enter-PSsession我能夠啓動一個遠程會話沒有問題...任何人都可以通知C#代碼中有什麼錯誤

回答

1

好吧我無法從C#代碼獲取Enter-PSSession cmdlet,但下面是我可以使用的代碼使用C#做PS遠程...

int iRemotePort = 5985; 
string strShellURI = @"http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; 
string strAppName = @"/wsman"; 
AuthenticationMechanism auth = AuthenticationMechanism.Negotiate; 

WSManConnectionInfo ci = new WSManConnectionInfo(
    false, 
    sRemote, 
    iRemotePort, 
    strAppName, 
    strShellURI, 
    creds); 
ci.AuthenticationMechanism = auth; 

Runspace runspace = RunspaceFactory.CreateRunspace(ci); 
runspace.Open(); 

PowerShell psh = PowerShell.Create(); 
psh.Runspace = runspace; 

您現在可以使用PSH遠程運行命令。