Why does PowerShell class not load a snapin

巧了我就是萌 提交于 2019-12-01 13:38:45
Jaap

I finally found a hint how to configure a remote session (see https://superuser.com/a/518567).

You need to register a session configuration on the remote computer with

Register-PSSessionConfiguration -Name MyShell -StartupScript 'MyInitScript.ps1'

Then you can set the shellUri parameter of WSManConnectionInfo to http://schemas.microsoft.com/powershell/MyShell

The runspace you create this way will have the commands available which are imported by the MyInitScript.ps1 startup script.

So now this code will work:

        string shell = "http://schemas.microsoft.com/powershell/MyShell";
        var target = new Uri("https://myserver:port/wsman");
        var secured = new SecureString();
        foreach (char letter in "password")
        {
            secured.AppendChar(letter);
        }
        secured.MakeReadOnly();

        var credential = new PSCredential("username", secured);
        var connectionInfo = new WSManConnectionInfo(target, shell, credential);

        using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
        {
            runspace.Open();

            using (var ps = PowerShell.Create())
            {
                ps.Runspace = runspace;
                ps.AddCommand("Get-NAVServerInstance");
                var output = ps.Invoke();
            }
        }

Try invoking AddScript like so:

.AddScript("...", false)

this will execute the command in the global scope instead of a new local scope.

I think the proper way to do this is to use the RunspaceConfiguration class. It has an AddPSSnapin method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!