2013-05-13 40 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远程运行命令。