在C#中使用PSObject进行迭代

时间:2017-07-01 07:27:13

标签: c# powershell

我正在尝试获取Link实例的属性值。

但它一直给我空例外

我使用的代码如下。

var xs = PowerShell.Create()
        .AddScript("Get-ADComputer -Identity COM-PC-003$ -Properties * | select operatingsystem, accountexpires")
        .AddCommand("out-string");
Collection<PSObject> results = xs.Invoke();
//Console.WriteLine(xs);
foreach (var str in results)
{
    Console.WriteLine(str.Members["operatingsystem"].Value.ToString());
    Console.ReadLine();
    //System.Diagnostics.Debug.WriteLine(str.Properties["operatingsystem"].Value);
}

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样做:

while (true) {
    Console.WriteLine("Enter Hostname");
    var hn = Console.ReadLine();
    var xs = PowerShell.Create().AddScript(
               "$comp = Get-ADComputer -Identity " + hn +
               " -Properties *" + Environment.NewLine +
               "$obj = New-Object -TypeName psobject" +
               " -Property @{Host=$comp.operatingsystem;accountexpires = $comp.accountexpires}" +
               Environment.NewLine +
               "$obj1 = $obj | select -ExpandProperty Host ; $obj2 = $obj | select -ExpandProperty accountexpires ; $out = $obj1 + ' ; ' + $obj2 ; $out").AddCommand("out-string");
    Collection<PSObject> results = xs.Invoke();
    //Console.WriteLine(xs);
    foreach (var str in results)
    {
        Console.WriteLine("You want to see only OS vers? If its true - enter H, also enter E for see accountexpires or A for see all info");
        ConsoleKeyInfo c = Console.ReadKey();

        if (c.KeyChar == 'H')
        {
             Console.WriteLine(str.ToString().Split(';')[0]);
             Console.ReadLine();
        }

        if (c.KeyChar == 'E')
        {
             Console.WriteLine(str.ToString().Split(';')[1]);
             Console.ReadLine();
        }

        if (c.KeyChar == 'A')
        {
            Console.WriteLine(str.ToString());
            Console.ReadLine();
        }
    }
}