foreach frustration

This topic contains 0 replies, has 1 voice, and was last updated by Profile photo of Forums Archives Forums Archives 5 years, 4 months ago.

  • Author
    Posts
  • #6413

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

    Hi,
    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:

    powershell]
    $i = 0;
    foreach ($user in $UsersList.Items) {
    $i++
    $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) {
    $j++;
    $eOrderbook = $false
    if ($usersmembership -eq $null) {
    Write-host '$usersmembership is Null'
    break;
    }

    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.

You must be logged in to reply to this topic.