Quick tip: SharePoint powershell – get items in a list based on custom columns and other hints

This may be handy when trying to find specific items in a list based on values of various fields:

$web = Get-SPWeb http://yourweb
$list = $web.Lists["Your Library Name"]

// this is the bit - get items of a particular content type
// ? is shorthand for where, and $_ is the item in the pipeline
$listItems = $list.Items | ?{$_.ContentType.Name -eq "Content Type Name"}

// or items based on a custom column - if using -like then the wildcard is *
$listItems = $list.Items | ?{$_["InternalFieldName"] -like "*this*"

// you could join them up using -and
$listItems = $list.Items | ?{$_.ContentType.Name -eq "Content Type Name" -and $_["InternalFieldName"] -like "*this*"

// or iterate the loop and print them out
foreach($item in $listItems) { Write-Host $item.Name, $item["InternalFieldName"] }

or more directly

$list.Items | ?{$_.ContentType.Name -eq "Content Type Name" -and $_["InternalFieldName"] -like "*this*" | foreach { $_.Name, $_["InternalFieldName"]

// or count them
$listItems.Count

or

$list.Items | ?{$_.ContentType.Name -eq "Content Type Name" -and $_["InternalFieldName"] -like "*this*" | foreach {$count++}
$count

Powershell can be infuriating – but when you find the syntax, it can be pretty helpful.

P.S For a bonus tip, next time you’re in Powershell, hit F7 ;)



Tags: , , , , ,

4 Responses to “Quick tip: SharePoint powershell – get items in a list based on custom columns and other hints”

  1. You sir are a rockstar.

  2. Lucas Sawyer says:

    Hi Matt,

    I can’t seem to get this to work:
    $listitems = $list.items | ?{$_["InternalFieldName"] -like “*this*”}

    What I am trying to do is read the contents of the column “Computer”, and use it in a foreach loop (each line with have a different computer name I need to run a test-path command)

    foreach($item in $listitems)
    {
    if ((test-path “\\$item\c$\file.txt”) -eq “True”)
    }…

    Above doesn’t seem to do it. I am lost, please help.

    Thanks!

  3. Hi Lucas

    Stupid question time…. You changed “internalfieldname” for “computer” (or whatever your field is called), right?

    Failing that, what actually happens?

    You can try getting the field by doing something like

    $field = $list.fields["computer"]

    And call e.g.

    $field.description.

    If that doesn’t work, post some more code…

Leave a Reply