繁体   English   中英

在C#中使用PSObject进行迭代

[英]Iterating through with PSObject in C#

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

但是它总是给我空异常

我使用的代码如下。

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);
}

我该如何解决这个问题?

您可以尝试这样做:

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();
        }
    }
}

暂无
暂无

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

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