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

[玩转系统] 使用 PowerShell 将用户从 Excel (CSV) 导入到 SharePoint

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

使用 PowerShell 将用户从 Excel (CSV) 导入到 SharePoint


要求:有很多用户并希望将他们添加到 SharePoint?使用下面的脚本通过 PowerShell 以编程方式将用户批量添加到 SharePoint 组。此脚本从 Excel 导入用户列表。 CSV 文件到 SharePoint 并将它们添加到适当的组中。

解决方案:让我们使用 PowerShell 将用户从 Excel 导入到 SharePoint。以下是我的 CSV 文件,其中包含 SharePoint 中的用户及其目标组列表:

[玩转系统] 使用 PowerShell 将用户从 Excel (CSV) 导入到 SharePoint

用于将用户从 CSV 导入到 SharePoint 的 PowerShell 脚本:

以下是用于从 CSV 文件将用户批量添加到 SharePoint 组的 PowerShell:


Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

#Variables
$UserListCSV = "C:\UsersToImport.csv"
$SiteURL ="https://Sales.Crescent.com"

# Import the CSV file
$UserList = Import-CSV $UserListCSV #-header("GroupName","UserAccount") - If CSV doesn't has headers

#Get the Web
$Web = Get-SPWeb $SiteURL

#Iterate through each user from CSV file
foreach ($user in $UserList)
{
    #Get the Group and User
    $Group = $web.SiteGroups[$User.GroupName]
    $User = $web.Site.RootWeb.EnsureUser($User.UserAccount)
    #Add user to Group
    $Group.AddUser($User) 

    Write-Host "$($User) Added Successfully!" -ForegroundColor Green
}

#Dispose web object
$Web.Dispose()

使用 PowerShell 将批量用户从 CSV 文件导入到 SharePoint 网站:

我的另一个 CSV 文件有 AccountName(格式为“Domain\UserName”和“GroupName”)。

[玩转系统] 使用 PowerShell 将用户从 Excel (CSV) 导入到 SharePoint

用于将用户添加到 SharePoint 组的 PowerShell 脚本

这次我们添加一些错误处理。


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Import the List of Users from a .csv file,
$UserList= Import-CSV "C:\UserList.csv"
 
#Get the Web
$web = Get-SPWeb "https://sharepoint.crescent.com/sites/marketing"
 
foreach ($Row in $UserList)
{
  #Get the Group
   $Group = $web.Groups[$Row.GroupName]
 
 #Validate the user name
 try
   {
        $user = $web.Site.RootWeb.EnsureUser($Row.AccountName)
   }
   catch [system.exception]
   {
     write-host $_.Exception.Message
   }
 
   #Add user if valid user name is provided
    if($user -ne $null)
    {
       $Group.AddUser($user)
       write-host $user.AccountName
    }
}

#Dispose the web object
$Web.Dispose()

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

取消回复欢迎 发表评论:

关灯