Charlypop
Charlypop

Reputation: 176

Remove specific items from a list

I am creating a script that will help my colleagues to create a new AD user. This is what I have done so far:

ipmo activedirectory
$users = import-csv C:\Users\...\Desktop\test_bulk.csv -delimiter ";"
foreach ($User in $users) 
{
    $Displayname = $User.Givenname + " " + $User.Surname
    $Usersurname = $User.Surname
    $Userfirstname = $User.Givenname
    $SAM = $User.Samaccountname
    $OU = $User.path
    $password = $User.Password
    $newuser = New-ADUser -PassThru -Name $Displayname -SamAccountName $SAM -
    GivenName $Userfirstname -Surname $Usersurname -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force)-Enabled $true -Path $OU -ChangePasswordAtLogon $false -PasswordNeverExpires $true -OtherAttributes  @{businesscategory="Internal"}
    $gpuser = Get-ADPrincipalGroupMembership $User.gpuser | select -ExpandProperty name

    Add-ADPrincipalGroupMembership -Identity $newuser -MemberOf $gpuser
}

As you can see I have set a variable $gpuser so I can output a user's group membership to set all these into the new user's membership.

But there is a little hurdle... I need to remove up to three groups from the retrieved list. I mean each time I output a user's membership I need to remove a few groups IF they are present in the list.

The thing is I don't know how to script that and where to start.

Upvotes: 1

Views: 76

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58981

You should take a look at the Where-Object cmdlet and the -notin operator.

Basically you will do something like this:

$excludeFromThisList = @("group1", "group2")
$newGroupList = $gpuser | Where-Object { $_ -notin $excludeFromThisList }

Upvotes: 2

Related Questions