這幾個月一直在幫客戶改需求,部署。我已經心力憔悴,經過一段時間的摸索,我對用PowerShell實現自動化部署也有了一些心得,比如說利用PowerShell匯出匯入AD中的User。在基於SharePoint平台開發時,利用AD來進行人員的管理,一般會建組織單元(OrganizationalUnit)來對使用者進行管理。當最終部署到客戶的伺服器上時,怎樣把本地AD中的使用者資料同步到伺服器上呢,要知道如果手動輸入人員是一件麻煩的事。幸運的事,PowerShell可以幫我們解決這個麻煩的問題。
匯出AD Users(Export-Csv)
首先匯出本地相應OU中的User Object
<# .Description 從AD中的組織單元裡以csv格式匯出人員資料 .Example .\userInfoExport.ps1 -ou "Sources" -dc "xcgov" -path "c:\temp\xxx.csv" #> param([string]$ou,[string]$dc,[string]$path) if(!(Get-PSSnapin| Where-Object{$_.Name -eq "Microsoft.SharePoint.PowerShell"})){ Add-PSSnapin "Microsoft.SharePoint.PowerShell"} $searchBase='OU='+$ou+',Dc='+$dc+',Dc=com' Get-ADUser -LDAPFilter '(name=*)' -SearchBase $searchBase |Select GivenName,SurName,Name,SamAccountName|Export-Csv $path -NoTypeInformation -Encoding UTF8
匯出時注意編碼格式,特別是資料中包含中文等。比如我這兒使用的是UTF-8。
匯出的對象包含許多屬性,我們選重要的屬性匯出,比如GivenName、SurName、Name、SamAccountName,結果如下所示:
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/web/sharepoint/
匯入AD Users(Import-Csv)
當得到指定的OU中的User後,接下來就是匯入到線上伺服器AD指定的OU中
<# .Description 從指定的csv格式中匯入人員資訊 .Example .\importUserInfo.ps1 -ou "Hello" -dc "Kingdom" -sourcePath "C:\temp\xxx.csv" #> param([string]$ou,[string]$dc,[string]$sourcePath) if(!(Get-PSSnapin|Where-Object{$_.Name -eq "Microsoft.SharePoint.PowerShell"})){ Add-PSSnapin "Microsoft.SharePoint.PowerShell" } #建立組織單元# [string]$path='OU='+$ou+',Dc='+$dc+',Dc=Com' if(![adsi]::Exists("LDAP://$path")){ $domainObj=[adsi]("LDAP://Dc="+$dc+",Dc=com") $domainOU=$domainObj.Create("OrganizationalUnit","OU="+$ou) $domainOU.SetInfo()} $users=Import-Csv -Path $sourcePath foreach($user in $users){ $givenName=$user.GivenName $surName=$user.SurName $name=$user.Name $samAccountName=$user.SamAccountName $userPrincipalName=$samAccountName+'@'+$dc+'.com' $password=$user.Password #建立AD User# New-ADUser -Name $name -SamAccountName $samAccountName -UserPrincipalName $userPrincipalName -DisplayName $name -GivenName $givenName -Surname $surName -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) -PasswordNeverExpires $true -Enabled $true -Path $path } Write-Host "匯入成功"
如果匯入的時候一直出現亂碼,但用Excel開啟csv格式時都是正確的編碼。嘗試將csv用記事本開啟,另存新檔UTF-8格式。因為我使用的英文版的Server,不知道中文版本的系統是否會出現匯入亂碼。
匯入成功後,如下所示:
小結
這篇部落格對PowerShell自動化部署SharePoint開了個頭,下一篇隨筆打算寫寫利用SPSD進行自動化部署SharePoint,包括利用PowerShell建立許可權組,分配許可權,設定主版頁面等。
作者資訊:cnblogs 木宛城主