PnP PowerShell and more...

Here I occasionally post about Microsoft 365 Patterns and Practices in general and PnP PowerShell more specifically.

Speed tip for PnP PowerShell

2022-12-06 1 min read PowerShell

Did you know that retrieving 20 list items like this

for($i=1;$i -lt 20;$i++)
{
    Get-PnPListItem -List "My List" -Id $i
}

is so much slower than

$list = Get-PnPList "My List"
for($i=1;$i -lt 20;$i++)
{
    Get-PnPListLitem -List $list -Id $i
}

?

The reason behind this is that the cmdlet Get-PnPListItem for every execution where you use the name ‘My List’ will have to make an extra call to the server to figure out the details about that list before it is able to retrieve the item.

So a simple speed trick is to first retrieve the details of that list and store it in a variable ($list), and then provide the Get-PnPListItem cmdlet with that list object instead of the list name. That way the cmdlet has all the information of that list, and it does not have to retrieve that same information 20 times as shown in the example above.

Notice this works with a lot of cmdlets, if you look at the help for a cmdlet and you see a parameter is a so called ‘pipebind’ variable, it means it accepts multiple types of values. The List cmdlets for instance always accept a string (e.g. the name) of a list, but also an actual list object.