使用C#创建PowerShell远程会话

时间:2017-02-08 05:14:41

标签: c# powershell

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

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();
}

2 个答案:

答案 0 :(得分:1)

我无法测试这一点,但它可能会让你走上正轨:

        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);

        string scriptPath = $@"
        $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://servername/poweshell -Credential {remoteCredential} | Out-String
        Import-PSSession $Session";

        Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        Pipeline pipeline = runspace.CreatePipeline();
        string scriptfile = scriptPath;
        Command myCommand = new Command(scriptfile, false);
        pipeline.Commands.Add(myCommand);
        pipeline.Invoke();
        runspace.Close();

答案 1 :(得分:0)

我有一篇文章描述了一种简单的方法,可以通过http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/上的.NET通过WinRM运行Powershell,或者可以直接在https://github.com/NaosProject/Naos.WinRM上获取代码。

多年来我一直在使用任何参数编码问题,它极大地简化了这些操作的运行...

如果您只想复制代码,则代码在单个文件中,它也是一个NuGet程序包,其中包含对System.Management.Automation的引用。

// this is the entrypoint to interact with the system (interfaced for testing).
var machineManager = new MachineManager(
    "10.0.0.1",
    "Administrator",
    MachineManager.ConvertStringToSecureString("xxx"),
    true);

// can run random script blocks WITH parameters.
var fileObjects = machineManager.RunScript(
    "{ param($path) ls $path }",
    new[] { @"C:\PathToList" });

希望这会有所帮助,我在自动化部署中已经使用了一段时间。如果发现问题,请发表评论。