当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在 SharePoint 中通过显示名称获取用户帐户

作者:精品下载站 日期:2024-12-14 21:06:13 浏览:13 分类:玩电脑

在 SharePoint 中通过显示名称获取用户帐户


要求:通过 SharePoint 中的显示名称获取用户

我们有一个 CSV 文件,其中包含项目列表及其团队领导信息。此列表将在 SharePoint 列表上更新。但挑战是“团队负责人”字段显示的是用户的显示名称,而不是帐户名称(域\登录 ID)。因此,在更新到 SharePoint 列表之前,我们需要用户的显示名称中的登录 ID。

解决方案:让我们在 Active Directory 中查询给定的显示名称,以获取用户的登录 ID。

先决条件:您需要拥有 Active Directory 的 PowerShell 模块安装使用的目录:导入模块ActiveDirectory!使用 PowerShell cmdlet:Add-WindowsFeature RSAT-AD-PowerShell 将 PowerShell 的 AD 模块添加到您的服务器/桌面!否则,您将收到一条错误消息:“Import-Module:未加载指定的模块“ActiveDirectory”,因为在任何模块目录中均未找到有效的模块文件”。

用于从显示名称获取用户帐户并更新 SharePoint 列表的 PowerShell 脚本:


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Import-Module ActiveDirectory

#Configuration Variables
$SiteURL = "https://intranet.crescent.com/"
$ListName = "Projects"                
$FieldName="Team Lead"
$CSVFile ="C:\Temp\TeamLeads.csv" 

#Custom Function Get User Account from Display Name in AD 
Function Get-UserAccount($DisplayName)
{
    $UserAccount=Get-ADUser -LDAPFilter "(displayName=$DisplayName)" | Select sAMAccountName
    if($UserAccount.sAMAccountName -ne $null)
    {
        return $UserAccount.sAMAccountName.tostring()
    }
    else
    {
        write-host $DisplayName not found in AD! -f Red
        return $null
    }
} 
#Import from CSV file - CSV has Headers ("ProjectName", "TeamLead")
$CSVData = Import-CSV -path $CSVFile

#Get the Target Web & List
$Web = Get-SPWeb -identity $WebURL
$List = $web.Lists[$ListName]
 
#Iterate through each Row in the CSV file
foreach ($Row in $CSVData) 
{
    #Filter by Project Name
    $Item = $List.Items | Where-Object { $_["Project Name"] -eq $Row.ProjectName }
  
    #If the matching project found
    If($Item -ne $null)
    {
        write-host "Searching for:"$Row.TeamLead
        #Get the User Account from Display Name
        $UserAccount = Get-UserAccount $Row.TeamLead
  
        #If User account found in AD
        if($UserAccount -ne $null)
        {
            $TeamLead=$web.ensureuser($UserAccount)
     
            #Update Team member field
            $item["Team Lead"] = $TeamLead
            $item.Update()
            Write-Host "Updated Project:"$Row.ProjectName -ForegroundColor Green
        }
       else
       {
            write-host "No matching User Account Found for :"$Row.TeamLead -f Red
       }
    }
    else
    {
        write-host "No matching List Item Found for:"$Row.ProjectName -f Red
    }  
}

使用 SPUtility 的 ResolvePrincipal 方法:

您还可以使用 SPUtility 的 ResolvePrincipal 方法通过显示名称获取用户,而不是查询 Active Directory:


$Web = Get-SPWeb "https://intranet.crescent.com"
$DisplayName="Barunx Romeih"
$Principal = [Microsoft.SharePoint.Utilities.SPUtility]::ResolvePrincipal($web, $DisplayName, "All", "All", $null, $false)
$Principal.LoginName

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯