Most of all I use PowerShell for administration of SharePoint portal. But also I use it when I need to make some actions with SharePoint lists – get items, update items, remove items (link how to remove items) or to make report based on lists on SharePoint.

The task is to get list items and display columns ID and Title using PowerShell (ID space Title). Simple task but with pitfalls.

Source data: SharePoint web and list

 

$web = Get-SPWeb("https://spdev/depTasks/")
$list = $web.Lists["myTasks"]
$item = $list.GetItemById(20955)

 

I tried 4 ways to concatenate values "ID" + space + "Title", but only 2 of them are correct. Here they are:

 

$str1 = $item['ID'] +  ' ' + $item['Title'] #incorrect
$str2 = "$item['ID']  $item['Title']"
$str3 = $item['ID'].Tostring() +  ' ' + $item['Title'].Tostring()
$str4 = [string]$item['ID'] + ' ' +  [string]$item['Title']

Write-Host "1:"  $str1
Write-Host "2:"  $str2
Write-Host "3:"  $str3
Write-Host "4:"  $str4

 

The result

For $str1 there is the error in concatenating:

Cannot convert value " " to type "System.Int32". Error: "Index was outside the bounds of the array."
At C:\Users\admin\Desktop\itemsList.ps1:14 char:22
+ $str1 = $item['ID'] + <<<<   " " + $item['Title']
+ CategoryInfo          : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException

For $str2 the result is "Microsoft.SharePoint.SPListItem['ID']  Microsoft.SharePoint.SPListItem['Title']". Not what I expected to get.

For $str3 and $str4 I've got what I wanted to.

PS: Usually I write code in C# for SharePoint – web parts, timer jobs or just console utilities for actions with SharePoint data. But there are a lot of useful actions that you can do in PowerShell much faster. So, once I started to make local solutions for SharePoint in PowerShell.