远程PowerShell中的自定义cmdlet条目

时间:2017-03-02 15:52:43

标签: c# powershell runspace pscmdlet

我已经尝试了几天将自定义cmdlet添加到C#中远程PowerShell的运行空间

string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
        System.Security.SecureString sString = new System.Security.SecureString();
        foreach(char passwordChar in password.ToCharArray())
        {
            sString.AppendChar(passwordChar);
        }
        PSCredential credential = new PSCredential(username, sString);
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, computerName, 5985, "/wsman", shellUri, credential);
        try {
            using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
            {
                runspace.Open();
                pipe = runspace.CreatePipeline();
                pipe.Commands.AddScript(script);
                    Collection<PSObject> result = pipe.Invoke();
                    foreach (PSObject line in result)
                    {
                        scriptOutput.Add(line.ToString());
                    }
                pipe.Dispose();
                runspace.Close();
            }

我有类似的东西可以在远程机器上执行脚本。但我需要添加一个自定义cmdlet。

我知道使用本地PowerShell,您可以像这样使用InitialSessionState:

InitialSessionState iss = InitialSessionState.CreateDefault();
        SessionStateCmdletEntry gfv = new SessionStateCmdletEntry("Get-Custom", typeof(GetCustomCommand), null);
        iss.Commands.Add(gfv);
        using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))

GetCustomCommand扩展PSCmdlet。

但是使用远程PowerShell,您无法使用InitialSessionState初始化运行空间。 如何将SessionStateCmdLetEntry添加到我的远程运行空间?

有人可以帮助我吗?感谢

0 个答案:

没有答案