I want to get PSObject result in a table, but I get error:System.NullReferenceException: 'Object reference not set to an instance of an object.'

  • Thread starter Thread starter Protecteric
  • Start date Start date
P

Protecteric

Guest
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
using System.Data.OleDb;
using System.Data;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
RunScript s = new RunScript();
s.Script = "Get-Service";

s.ScriptResult();
Console.WriteLine(s.ResultScript);
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e);
Console.ReadKey();
}
}
}
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
public class RunScript
{

public string Script { get; set; }
public object ResultScript { get; set; }

public void ScriptResult()
{
Runspace runspace = RunspaceFactory.CreateRunspace();

runspace.Open();

Pipeline pipelineimport = runspace.CreatePipeline();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(Script);
pipeline.Commands.Add("Out-String");

Collection<PSObject> results = pipeline.Invoke();

runspace.Close();

DataTable tempTable = new DataTable();
tempTable.Columns.Add("Status");
tempTable.Columns.Add("Name");
tempTable.Columns.Add("DisplayName");


foreach (PSObject obj in results)
{
//ResultScript = obj;

DataRow row = tempTable.NewRow();
row["Status"] = obj.Properties["Status"].Value.ToString();
row["Name"] = obj.Properties["Name"].Value.ToString();
row["DisplayName"] = obj.Properties["DisplayName"].Value.ToString();
tempTable.Rows.Add(row);

}

}

}

}

Continue reading...
 
Back
Top