0

I have a list of PSObject items that are returned on calling the .Invoke() method while using the System.Management.Automation package. On debugging this, I can see the values of the objects that I want to print in the BaseObject and ImmediateBaseObject properties. However, on using the foreach loop to iterate through the results, and printing the BaseObjects of each item just prints the type of the item (System.Collections.ArrayList). How do I store the value of BaseObjects into a variable?

Here is the code and some screenshots:

using (var ps = PowerShell.Create())
{
    var results = ps.AddScript(File.ReadAllText(@".\PSScripts\test_func2.ps1")).Invoke();
    foreach (PSObject result in results)
    {
        if (result != null)
        {
             outList.Add(result.BaseObject.ToString())
        }
    }
}

This is the results object during debugging, which only has arrays of relevant data. Hidden due to privacy reasons. This is the result object, which only has arrays of relevant data

This is the result object > BaseObject view during debugging. The result object's members property does not have the relevant data. results object

And this is the output I get on executing the above code:

output on execution gives System.Collections.Arraylist as output

Thanks in advance.

  • If you are looking to receive back custom objects rather than ArrayLists you need to look at your ps1 script and modify it to return objects – Daniel Jul 15 '21 at 15:21
  • Thanks Daniel. I resolved the issue, but this seems like the better way to do it. Thing is, I already am returning an object array of basetype System.Array from the script. What could I change? – Devansh Purohit Jul 16 '21 at 04:34
  • 1
    I'd have to see your ps1 script to see how you are outputting a collection of arraylists instead of objects. You can post a new question with that code asking how you could change the output from arraylists to objects to get further help with that. Either way, happy for you that you found a solution for your issue. :) – Daniel Jul 16 '21 at 07:37

1 Answers1

0

I resolved this issue by creating an IList object and casting my result object to IList. I can then iterate through the values of the IList variable. Here, res is a List<String[]> object declared with function level scope that can hold all values of the results object.

List<string> temp = new List<string>();
IList collection = (IList)result.BaseObject;
foreach(var x in collection)
{
    temp.Add((string)x);
}
res.Add(temp.ToArray());
  • 1
    It looks to me that the only problem with your original code is that you called `.ToString()` on `result.BaseObject`, which predictably gives you the output you saw; try `([System.Collections.ArrayList] @()).ToString()` from a PowerShell window, for instance. – mklement0 Jul 16 '21 at 16:50