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 > BaseObject view during debugging. The result
object's members property does not have the relevant data.
And this is the output I get on executing the above code:
Thanks in advance.
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());