Jonathan Eckman
Jonathan Eckman

Reputation: 2077

Format Powershell list query

I am retrieving list items with a caml query using:

$list = $web.Lists["My List"]
$items = $list.GetItems($query)

I need to output this data in a readable format, such as a table. When I use:

$items | Format-Table

I get a table that is built using I dont know what. Its definitely not the list items. Heres the output:

ListItems                                           Parent List
---------                                           -----------
{Title of List Item 1, Title of List Item 2, ...}   My List
{Title of List Item 1, Title of List Item 2, ...}   My List
{Title of List Item 1, Title of List Item 2, ...}   My List

If I use a foreach loop to output the each item in items I get the correct data, but Im having trouble formatting it into a table. Here is how Im doing it:

foreach($item in $items) {
  Write-Host $item["Title"] ---- $item["Author"] ---- $item["Category"]
}

Which outputs:

Test Title 1 ---- Hemingway ---- Best Seller
The Title of Number 2 ---- Stein ---- Horror
Three ---- Shakespeare ---- Tragedy  

Not very readable. How can I either access the correct data in method 1, or format method two into a table?

Upvotes: 0

Views: 739

Answers (1)

Shay Levy
Shay Levy

Reputation: 126772

Create a custom table for each item and pipe it to Format-Table:

$items | Foreach-Object{
  New-Object PSObject -Property @{
    Title = $_["Title"]
    Author = $_["Author"]
    Category = $_["Category"]
  }
} | Format-Table

Upvotes: 2

Related Questions