Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Powershell syntax...

  • 01-06-2014 11:22AM
    #1
    Registered Users, Registered Users 2 Posts: 1,000 ✭✭✭


    I have a CSV file - two columns: Accountname, Groupname

    I have a loop that creates the Groupname
    I have a sub loop that checks the Accountname validity and adds the Accountname to the Groupname

    My sub loop works, it correctly adds the right Accountname to the right Groupname. But I get this error "You cannot call a method on a null-valued expression." even though I don't believe the value is Null.

    I believe my method runs successfully but is badly written :o

    foreach($group in $UserList)
    {     
        $GroupName = $group.GroupName
        if($web.SiteGroups[$GroupName] -ne $null)
        {
            write-host "$GroupName already exists"
        }
         else
        {
            write-host "$GroupName does not exist, creating new $GroupName group"
            $web.SiteGroups.Add($GroupName, $siteownergroup, $null, $description)
            $spgroup = $web.SiteGroups["$GroupName"]
            $spgroup.Update()      
            
            foreach($Row in $UserList)
            {
                #### Get the Group name
                $UserGroup = $web.Groups[$Row.GroupName]
                $user = $web.site.RootWeb.EnsureUser($Row.AccountName)
                if ($user -ne $Null)
                 {
                   $UserGroup.AddUser($user)
                 }        
             }
        }
     }
    

    The ERROR message is

    You cannot call a method on a null-valued expression.
    At C:\Scripts\groups-externalcsv.ps1:49 char:14
    + $UserGroup.AddUser($user)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull


    It errors each time at $UserGroup.AddUser($user)


Comments

  • Closed Accounts Posts: 751 ✭✭✭SeanPuddin


    I've never used Powershell but is this legal? Capital N for null?

    if ($user -ne $Null)
    {
    $UserGroup.AddUser($user)
    }

    Very difficult to diagnose the problem without full script and line numbers.


Advertisement