Tuesday, January 3, 2023

Remove invalid user id from Sharepoint Fundation 2010 with powershell

 Whenever user from AD removed, The user id remained at sharepoint without automatically remove.

Here is the steps to remove invalid user using powershell:

1. get a list of user from sharepoint and save to a file

cmdlet: get-spuser -web http://portal select userlogin | sort userlogin | foreach{ $_.userlogin.remove(0,5) out-file spuser.txt

2 Open spuser.txt manually scan through and remove non user id such as itsupport, ifca, boss, etc

3. copy/move spuser.txt to AD server.

4. Open AD Powershell from AD server.

5. create a script file and with code below:

$content = get-content "$(get-location)\spuser.txt" # load the list of user id from spuser.txt file.


out-file remove-list.txt   #generate a user list that need to be removed at sharepoint server

foreach ($line in $content)
{
    try {
        
get-aduser $line -ErrorAction stop | selectsamaccountname -expandproperty samaccountname 
    }  # try
catch 
{
                "absb\" + $line | out-file -append remove-list.txt

           }  # catch
 } # foreach


6. Once remove-list generated, copy to sharepoint server 

7. create a script file with code below:

set-variable -name portal -value "http://portal" -option constant

$content = get-content "$(get-location)\remove-list.txt"

out-file deleted.txt # to record deleted id

foreach ($line in $content) {

    remove-spuser $identity $line -web $portal $confirm:$false

    try{
            get-spuser $line -web $portal -ErrorAction stop
        } # try
catch {
            $line + " -deleted." | out-file -append deleted.txt

           } # catch

} # foreach