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

[玩转系统] SharePoint Online:PowerShell EnsureUser 方法

作者:精品下载站 日期:2024-12-14 15:16:29 浏览:14 分类:玩电脑

SharePoint Online:PowerShell EnsureUser 方法


SharePoint Online 中的“EnsureUser”方法是什么?
顾名思义,SharePoint Online 中的“EnsureUser”方法检查给定的用户帐户是否有效,然后将用户对象添加到“用户信息”列表”。您还可以使用此方法从给定的用户名获取 User 对象。

使用 PowerShell 确保用户在 SharePoint Online 中

PowerShell 中的 EnsureUser 方法用于确保 SharePoint Online 网站集中存在特定的用户帐户。如果指定的用户帐户不存在,该方法将使用指定的电子邮件地址或用户名创建新的用户帐户,而不授予任何权限。

以下是 SharePoint Online EnsureUser 方法的示例 PowerShell 脚本:


#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Function to check if a user account is valid
Function Ensure-SPOUser()
{
    Param( 
        [Parameter(Mandatory=$true)] [string]$UserID,
        [Parameter(Mandatory=$true)] [string]$SiteURL
        )
    Try {
        #Setup Credentials to connect
        $Cred = Get-Credential

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
      
        #ensure sharepoint online user
        $Web = $Ctx.Web
        $User=$web.EnsureUser($UserID)
        $Ctx.ExecuteQuery()
        Return $True
    }
    Catch {    
        #write-host -f Red "Error:" $_.Exception.Message
        Return $False
    }
}

#Variables
$SiteURL = "https://crescent.sharepoint.com/Sites/marketing"
$UserID = "[email protected]"
  
#Call the function to check if the user account is valid
Ensure-SPOUser -UserID $UserID -SiteURL $SiteURL

此脚本检查给定的用户帐户是否有效,如果用户帐户有效,则返回“True”,否则返回 False。

如果您在 SharePoint Online 中收到“找不到指定的用户”错误,则可能是给定的用户 ID 在 SharePoint Online 租户的 Azure AD 中不存在!

PnP PowerShell 中的 EnsureUser 方法

虽然上面的代码可以转换为 PnP PowerShell 方法,但下面是更简洁的方法:


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$UserEmail = "[email protected]"

Try {
    #Connect to PnP Online
    Connect-PnPOnline $SiteURL -Interactive

    #Resolve the User
    $User = Get-PnPUser | Where-Object Email -eq $UserEmail
    If($User -eq $null) {        
        $User = New-PnPUser -LoginName $UserEmail
    }

    #Return the User Object
    $User
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

总之,PowerShell 中的 EnsureUser 方法是一种用于检查 SharePoint Online 网站集中是否存在特定用户帐户的工具。通过使用此方法,您可以验证特定用户帐户并将其添加到网站集(如果不存在)。

这是检查 SharePoint Online 中是否存在用户的另一篇文章:PowerShell to check if a user isn't in SharePoint Online

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

取消回复欢迎 发表评论:

关灯