I have never worked with Powershell or Sharepoint before, trying to help a friend, so my mistake might be really obvious, I apologise in advance.
So what I'm trying to do here is: -loop through all user profiles and... -loop through my already existing list in a nested foreach loop -compare DisplayName of current user to current list item's "Employee" field. If there's a match, update every field of that list item. -if we looped through the whole list and there was no match, add a new list item.
This is what I found and helped me a lot:
http://mysharepointwork.blogspot.no/2010/09/addupdatedelete-list-items-using.html
Here is my code:
#Add SharePoint PowerShell SnapIn if not already added
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$site = new-object Microsoft.SharePoint.SPSite("http://sp2016:85/");
$ServiceContext = [Microsoft.SharePoint.SPServiceContext]::GetContext($site);
#Get UserProfileManager from the My Site Host Site context
$ProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext)
$AllProfiles = $ProfileManager.GetEnumerator()
#Open SharePoint List
$SPServer="http://sp2016:85/"
$SPAppList="/Lists/UPList2/"
$spWeb = Get-SPWeb $SPServer
$spData = $spWeb.GetList($SPAppList)
foreach($profile in $AllProfiles)
{
#Add properties to this list item
$DisplayName = $profile.DisplayName
$Office = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::Office].Value
$WorkPhone = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::WorkPhone].Value
foreach($Items in $spData)
{
$SPItem = $spData.Items
if ($DisplayName -match $SPItem["Employee"] )
{
$SPItem["Office"] = $Office
$SPItem["Extension"] = $WorkPhone
$SPItem.Update()
{break}
}
}
#Create a new item
$newItem = $spData.Items.Add()
#Fill
$newItem["Employee"] = $DisplayName
$newItem["Office"] = $Office
$newItem["Extension"] = $WorkPhone
write-host "Profile for account ", $DisplayName
$newItem.Update()
}
write-host "Finished."
$site.Dispose()
-The adding new item part seems to work, but not the update one. I assume,either my if statement or my second for loop is the problem.
Every help is appreciated and/or feedback on how to post questions more efficiently. Stack Exchange rookie alert. Thank you all!