Tuesday, November 18, 2014

How to update User profile using powerShell

When I was working with one of the client .I was asked to set couple of values in user profile . Here is small power shell script which will be handy when trying to edit User profile on SharePoint 2010 User profile service.
1. This will read csv file.
2. Will write output file.

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
# SharePoint site URL
$site = new-object Microsoft.SharePoint.SPSite("http://XXXXXX:xxxx/");  # central Admin url
$ServiceContext = [Microsoft.SharePoint.SPServiceContext]::GetContext($site);
$ProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext)
$results = @()
$filePath = "C:\Deployments\PowerShell\output.csv"
#Loop Through all Profiles and write properties where condition is met 
Import-Csv C:\Deployments\PowerShell\profile1.csv |
ForEach-Object {
$AccountName=$_.AccountName
try {
        $profile = $ProfileManager.GetUserProfile($_.AccountName)
        If($profile -ne $null)
        {
        $prevValue= $profile["Flag"].Value
        If ($profile["Flag"].Value -eq $False)
        {
        $profile["Flag"].Value=$True
            $profile.Commit();    
        }  
            $NewVal=$profile["Flag"].Value  
            #write down to object for CSV export  
             $details = @{            
                        Account    = $AccountName             
                        PreVal     = $prevValue                 
                        NewValue   = $NewVal 
                        }                           
            $results += New-Object PSObject -Property $details  
           }
         }
     
    catch {
                "Exception when getting account " + $AccountName + " --> " + $error[0]
        }
  
$results | export-csv -Path $filePath -NoTypeInformation
}

write-host "Finished."
$site.Dispose() 

No comments: