Tuesday, June 24, 2014

SharePoint 2013 - Delete UserProfile Data with PowerShell

Description:
This PowerShell script will take two input files Users.csv (with all the user names under USERID column) and Properties.csv (with all the properties under TITLE column) and delete the values of UPA properties for the given users.

Script:
#PowerShell Script - Delete User Profile Properties Data in MySite 2013 UPA

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

function WriteLog
{
    Param([string]$message, [string]$logFilePath)
    Add-Content -Path $logFilePath -Value $message
}


#################################################################################################

$logFile = "D:\PowerShellScripts\DeleteUserProfileDataInUPA\DeleteUserProfileDataInUPA.log"
$batchFile = "D:\PowerShellScripts\DeleteUserProfileDataInUPA\Users.csv"
$PropertiesFile = "D:\PowerShellScripts\DeleteUserProfileDataInUPA\Properties.csv"
$mysiteHostUrl = "http://company.MySite.com"


$mysite = Get-SPSite $mysiteHostUrl
$context = [Microsoft.Office.Server.ServerContext]::GetContext($mysite)
$upm =  New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)

$currentProfile = 0

$Properties = Import-CSV $PropertiesFile

$users = Import-CSV $batchFile
$totalProfiles = $users.Count
ForEach ($user in $users) 
{
    
    $currentProfile ++;
    $AccountName = $user.USERID
    
    $profile = $upm.GetUserProfile($AccountName)

    try
    {       
        
        forEach ($Property in $Properties)
        {
            $PropertyTitle = $Property.TITLE

            $OldValue = $profile[$PropertyTitle].Value;

            $profile[$PropertyTitle].Value = $null;
            $profile.Commit() 

            $now = [System.DateTime]::Now
            $msg = $now.ToString() +  " : Deleting value from "+ $PropertyTitle +": "+ $OldValue +" for " + $AccountName + " (" +$currentProfile + " of " + $totalProfiles + ")"
            write-host $msg
            WriteLog $msg $logFile

        }
        
    }
    catch [system.exception]
    {
        $msg = $Error[0].Exception.InnerException.InnerException.Message
        write-host -f red $msg
        WriteLog $msg $logFile
    }
        
    $profile = $Null
    $user = $Null
}


$mysite.Dispose(); 


No comments:

Post a Comment

Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...