使用C#创建PowerShell远程会话 [英] Creating powershell remote session using C#

查看:89
本文介绍了使用C#创建PowerShell远程会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用C#从我的.Net应用程序创建与PowerShell的连接。在我尝试创建会话时完成连接后,它会返回空集合。



我尝试过:



I've been trying to create a connection with PowerShell from my .Net application using C#. After connection is done when I try to create a session, it returns empty collection.

What I have tried:

string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";

PSCredential remoteCredential = new PSCredential("userID", StringToSecureString("Password"));

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "Ip Address of server", 5985, "/wsman", shellUri, remoteCredential, 1 * 60 * 1000);

runspace = RunspaceFactory.CreateRunspace(connectionInfo);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

runspace.Open();

using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;

ps.AddScript(@"$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://servername/poweshell -Credential " + remoteCredential);

//result count returned is 0 
var result = ps.Invoke();

ps.Commands.Clear();

ps.AddCommand("Import-PSSession $Session");

ps.Invoke();
}

推荐答案

Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http:// servername / poweshell -Credential + remoteCredential);

// 返回的结果计数为0
var result = ps.Invoke();

ps.Commands.Clear();

ps.AddCommand( Import-PSSession
Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://servername/poweshell -Credential " + remoteCredential); //result count returned is 0 var result = ps.Invoke(); ps.Commands.Clear(); ps.AddCommand("Import-PSSession


Session);

ps.Invoke();
}
Session"); ps.Invoke(); }


这篇关于使用C#创建PowerShell远程会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆