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

[玩转系统] SharePoint Online:PowerShell 检查用户是否存在

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

SharePoint Online:PowerShell 检查用户是否存在


要求: SharePoint Online PowerShell 检查用户是否存在。

[玩转系统] SharePoint Online:PowerShell 检查用户是否存在

很多时候您需要检查 SharePoint Online 中是否存在用户。也许您正在尝试查看新用户帐户是否仍处于活动状态,或者您正在追踪 SharePoint Online 环境中某人的电子邮件或帐户的有效性。 PowerShell 使这个过程变得快速而简单,所以让我们看看它是如何完成的。我们将为您提供两种方法来检查用户的存在。第一种方法使用 MSOnline PowerShell 模块,第二种方法使用 SharePoint Online CSOM 和 PowerShell。

选项 1:使用 Azure AD Cmdlet 检查用户是否存在于租户中

在不同的情况下,您可能需要检查 Office 365 租户中是否存在用户,以下是我的 PowerShell 脚本。我们可以使用 Azure AD 的 Get-MsolUser cmdlet 来检查给定的用户帐户是否有效。


Import-Module MSOnline

#User Account Variable
$UserAccount = "[email protected]"

Try {
    #Get Credentials to connect
    $Cred = Get-Credential
 
    #Connect to Azure AD
    Connect-MsolService -Credential $Cred

    #Function to check if a user account exists in the tenant
    Function Check-UserExists()
    {
        Param( [Parameter(Mandatory=$true)] [string]$UserID )
     
        $User = Get-Msoluser -UserPrincipalName $UserID -Erroraction SilentlyContinue
        if ($User -ne $null)
        {
            Return $True
        }
        else
        {
            Return $False
        }
    }
    #Call the function to validate the user account
    Check-UserExists $UserAccount
}
Catch {    
    write-host -f Red "Error:" $_.Exception.Message
}

选项 2:SharePoint Online Ensure User 验证用户的方法

以下是使用 PowerShell 验证用户的本机 SharePoint 方法:“EnsureUser”方法。


#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 {    
        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

当您想要以编程方式确定用户是否存在于 SharePoint 中(或孤立)并根据结果采取适当的操作时,这些方法非常有用。

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

取消回复欢迎 发表评论:

关灯