使用Power Shell从AD获取并迭代计算机对象

时间:2017-11-01 18:02:50

标签: c# shell powershell active-directory

我在Power shell中有一个查询,它是从我的c#代码执行的。

 public void RunPowerShell()
    {
        string command = "Get-ADComputer -Filter * " +
            "-Properties Displayname, CN, DNSHostName, DistinguishedName, lastLogon, Created, IPv4Address, lastLogonTimestamp, " +
            "OperatingSystem, OperatingSystemServicePack, OperatingSystemVersion, whenCreated, whenChanged, Enabled, PasswordLastSet, CanonicalName | Select-Object -first 10 | " +
            "select Displayname, CN, DNSHostName, DistinguishedName, lastLogon, Created, @{N='lastLogonTimestamp';" +
            " E={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}, OperatingSystem " +
            " ,PasswordLastSet, CanonicalName ";

        DataTable dt = new DataTable();

        dt = RunScript(command);

    }


    private DataTable RunScript(string scriptText)
    {
        Runspace runspace = RunspaceFactory.CreateRunspace();

        runspace.Open();

        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(scriptText);

        pipeline.Commands.Add("Out-String");

        var results = pipeline.Invoke();

        Logger.log("Got the results.");

        runspace.Close();

        DataTable ADdt = new DataTable();
        ADdt.Columns.Add("CN");
        ADdt.Columns.Add("DistinguishedName");
        ADdt.Columns.Add("OperatingSystem");
        ADdt.Columns.Add("lastLogonTimestamp");
        ADdt.Columns.Add("PasswordLastSet");

        int count = 0;

        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in results)
        {

            label1.Text = (count++).ToString();

            ADdt.Rows.Add(new string[] { Convert.ToString(obj.Properties["CN"]), Convert.ToString(obj.Properties["DistinguishedName"]),
                   Convert.ToString(obj.Properties["OperatingSystem"]), Convert.ToString(obj.Properties["lastLogonTimestamp"]),
                Convert.ToString(obj.Properties["PasswordLastSet"]) });

        }

        return ADdt;
    }

根据此代码,我在“results”变量中获取所有计算机对象信息。当试图迭代“结果”时,它只迭代一次,并且第一次在“obj”迭代变量中检索所有计算机对象数据。

我想迭代每个返回的计算机对象并检索不同的计算机对象属性并将其保存在要显示的数据表中。

Thnx提前。

0 个答案:

没有答案