繁体   English   中英

返回PSObject集合的c#调用方法

[英]c# call method that returns collection of PSObject

我是vb的c#新手,很难弄清楚如何运行方法。 我的完整代码如下。 我的问题是主要方法应该是什么。 我从论坛获得了一些功能,这些功能应该可以让我远程执行交换管理命令。 我正在尝试通过远程交换运行基本的powershell命令,以查看是否可以正常工作。

任何帮助将不胜感激。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;

namespace ExchPwrShellCmdletsTest
{
    class Program
    {
        static void Main(string[] args)
        {

        }

        public Collection<PSObject> GetUsersUsingBasicAuth(string liveIDConnectionUri, string schemaUri, PSCredential credentials, int count)
        {
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
                new Uri(liveIDConnectionUri),
                schemaUri, credentials);
            connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

            using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
            {
                return GetUserInformation(count, runspace);
            }
        }

        public Collection<PSObject> GetUserInformation(int count, Runspace runspace)
        {
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.AddCommand("Get-Users");
                powershell.AddParameter("ResultSize", count);

                runspace.Open();

                powershell.Runspace = runspace;

                return powershell.Invoke();
            }
        }
    }
}

public Collection<PSObject> GetUsersUsingBasicAuth(string liveIDConnectionUri, string schemaUri, PSCredential credentials, int count)正在您的代码中定义一个新方法。 因为它指定了Collection<PSObject> ,所以此方法的返回类型将为Collection<PSObject>的形式。 要调用按名称引用的方法,然后传入任何可用的参数。

var coll = GetUsersUsingBasicAuth("liveidconnectionurl","schemauri",new PSCredentials(...), 5 ); 为您定义的第一个方法。

您可以在以下代码中使用上面的代码片段(带有实际值):

static void Main(string[] args)
{
   var coll = GetUsersUsingBasicAuth("liveidconnectionurl","schemauri",new PSCredentials(...), 5 );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM