foreach frustration

by Killaspp at 2013-02-20 03:12:25

I have a very frustrating problem with a PS script which I have created to read data from two Sharepoint 2010 lists - one is ‘Users’ and the other ‘User Memberships’. The requirement is to generate automated emails to each user. The ‘foreach’ processing works fine for ‘users’ and I am able to cycle through each item in the list. However, for ‘User memberships’, after I have successfully retrieved the ‘current memberships’ for the current user into a collection, in the associated ‘foreach’ iteration for current memberships, the current membership is empty - despite there being entries in the collection.
This does not seem to be behaving in a logical way at all and any help would be gratefully received e.g. are there certain pre-requisites or defaults which are assumed when foreach is used?

The relevant code extract is:

$i = 0;
foreach ($user in $UsersList.Items) {
$oldUsername = $user[“CRS User Name”]
$newUsername = $user[“User Name”]

# check that this user has a Certificate Request System (CRS) User Name:
if ($user[“CRS User Name”] -ne $null -And $user[“CRS User Name”] -ne “”) {

# find any UserMemberships for this user
$j = 0;
$currentmembership = $UserMembershipsList.Items | where {$[“User Name”].LookupId -eq $user.Id}
Write-host '$currentmembership count = ’ $currentmembership.count

# check if eOrderbook or cFolders

foreach ($usersmembership in $currentmembership.Items) {
$eOrderbook = $false
if ($usersmembership -eq $null) {
Write-host ‘$usersmembership is Null’

if ($usersmembership[“Application”].LookupID -eq $appeOrderbookID) { # error here - Cannot index into a null array
Write-host ‘eOrderbook’
Write-Host $
[‘User Name’].LookupValue[/powershell][/code2]
by AlexBrassington at 2013-02-20 04:00:38
It looks like you might be trying to use ‘.items’ too much. You’re already taking the .Items from the list and putting them into an array. Once in the array the foreach operator knows to step through each item in the collection. Adding the .Items parameter will be pointing it to an empty value, hence the null reference error.
#It looks like you might be trying to use ‘.items’ too much.
$currentmembership = @(“Dave”,“Ken”,“Bill”)

foreach ($usersmembership in $currentmembership.Items) {
Write-Host $usersmembership

#Without the .items line
foreach ($usersmembership in $currentmembership) {
Write-Host $usersmembership
by Killaspp at 2013-02-20 09:28:54
OK, thanks for your quick response. I have now got it working.