Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey guys, I am able to run PowerShell scripts via an ASP.NET C# page and write single valued PS variables to a label. However, I can't figure out how to get or convert a PS array to a multidimensional array in ASP.NET C#.

Here is what I have so far. If "MyVar1" is an array in PS, how do I properly retrieve the data, convert it to a multidimensional array so I can bind into gridview?

I get "Cannot implicitly convert type 'object' to 'string[*,*]'. An explicit conversion exists (are you missing a cast?)" error when trying
C#
string[,] arrMultiD = Results;


Here is the code to run and get the PS results.
C#
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
var shell = PowerShell.Create();
string filePath = Server.MapPath("Scripts/MyScript.txt");
StreamReader reader = File.OpenText(filePath);
string powerShellCode = reader.ReadToEnd();
reader.Close();

shell.Commands.AddScript(powerShellCode);
var results = shell.Invoke();
var MyVar1 = shell.Runspace.SessionStateProxy.GetVariable("MyVar1");
runspace.Close();


Thanks!
Posted
Updated 27-May-13 20:55pm
v2

1 solution

I was able to figure this out, the test script file contains 2 lines...
$result = Get-Process
$result

C#
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
string filePath = Server.MapPath("Scripts/TestScript.txt");
StreamReader reader = File.OpenText(filePath);
string powerShellCode = reader.ReadToEnd();
reader.Close();
var shell = PowerShell.Create();
shell.Commands.AddScript(powerShellCode);
Collection<psobject> results = shell.Invoke();

DataTable tempTable = new DataTable();
tempTable.Columns.Add("Id");
tempTable.Columns.Add("Processname");

foreach (PSObject psObject in results)
{
    DataRow row = tempTable.NewRow();
    row["Id"] = psObject.Properties["Id"].Value.ToString();
    row["Processname"] = psObject.Properties["Processname"].Value.ToString();
    tempTable.Rows.Add(row);
}

GridView1.DataSource = tempTable;
GridView1.DataBind();
runSpace.Close();</psobject>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900