2
PowerShell psh = PowerShell.Create();
//psh.AddScript("Get-Service | Format-List -Property Name, Status");
psh.AddScript("Get-Service");

Collection<PSObject> result = psh.Invoke();

foreach (PSObject msg in result)
{
    Console.WriteLine(msg.Properties["Name"].Value);
}

In above example, if I use "Get-Service" alone, I am able to get the name and status of the service on the system. But if I use the same with "Get-Service | Format-List -Property Name, Status" get an exception.

1
  • 1
    I suggest to change format-list with a select-object instead. Commented May 23, 2013 at 8:11

1 Answer 1

5

When you run a command in PowerShell, the results are typically returned as CLR objects. So, your Get-Service command returns an object of type ServiceController, which is why you can query the name and status.

When you pass the output to Format-List, that command converts the objects into a list of objects that are designed for display of information: if you examine the results of Format-List you will see that it's a mixed array containing mostly FormatEntryData objects. Knowing this, it's obvious that you can't find the Status property on the output of Format-List: you no longer have a service object!

You can see the difference by running these two snippets, which will display the types of the objects in your results:

Get-Service | % { $_.GetType().FullName }

Get-Service | Format-List | % { $_.GetType().FullName }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for quick reply. Still need to ask is there a way to still get the information if it based on format-list or format-table in c#
@Vic Why would you want to? Format-List is used for formatting for display, not for further processing the data. Or is it a hypothetical question?
@Vic: You could manually parse it out of the strings, I imagine, but only for the properties that are displayed. I've no idea why you'd try though. Perhaps you should explain what you're trying to do instead, and maybe there's an alternative?
Getting data from "<>| Format-List <"> was actually a hypothetical question. Just wanted to know if it is possible. I am using psh.AddScript("Get-Service | Select-Object -Property Name, Status"); to get the name and status alone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.