1. 程式人生 > >SharePoint結合PowerShell建立入離職自動化(四)

SharePoint結合PowerShell建立入離職自動化(四)

client pro func 內容 .sh conn custom 理解 update

**首先說明,離職的腳本比較復雜,大概三百多行,各位如果理解起來有困難,可以根據註釋,分段研究!切勿直接復制,畢竟離職的操作影響還是蠻大的**

腳本工作流程如下,各位在使用時保存成ps1,然後放到任務計劃裏就可以啦:

技術分享圖片



#定義管理憑據
$pwd = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000035bf6730bcdda4eb12ed62660d5faed0000000002000000000003660000c0000000100000003ded59f253f488bd909320e6e53a89f30000000004800000a000000010000000709d6c5a15f7068c51c8a353ee79debb200000002cf42d5be95b64cc1c34489e330dc9a08f55d2e06474cadafa78c73c31e29c3d140000005ce706d435eb1d445cac9d1fc9ebe0ded07fbe75"

$Password = ConvertTo-SecureString -String $pwd
$Credential = New-Object System.Management.Automation.PSCredential("domain\admin",$Password)
#導入AD\SharePoint的管理單元和模塊
Import-Module ActiveDirectory
Add-PSSnapin Microsoft.SharePoint.PowerShell
#加載SharePoint用戶配置文件管理服務
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")
$contextWeb = New-Object Microsoft.SharePoint.SPSite("http://sharepoint:41843")
$ServerContext = [Microsoft.Office.Server.ServerContext]::GetContext($contextWeb)
$UserProfileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServerContext)
$Profiles = $UserProfileManager.GetEnumerator()
#建立Ex\Lync隱式會話
$ExSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mail.domain.cn/PowerShell/ -Credential $Credential -Authentication Kerberos
Import-PSSession $ExSession
$LyncSession = New-PSSession -ConnectionUri https://sip.domain.cn/OcsPowerShell -Credential $Credential
Import-PSSession $LyncSession
#定義報表頭
$ReportPath = "C:\Scripts\AutoDismission\";
$DeleteName = "AutoDelete_$(Get-Date -Format MMddhhmm).html";
$ReportName = "AutoDismission_$(Get-Date -Format MMddhhmm).html";
$ServiceReport = $ReportPath + $ReportName
$DeleteReport = $ReportPath + $DeleteName
$RedColor = "#FF0000"
$WhiteColor = "#FFFFFF"

$Header = "
        <html>
        <head>
        <meta http-equiv='Content-Type' content='text/html; charset=gb2312'>
        <title>Service Report</title>
        <STYLE TYPE='text/css'>
        <!--
        td {
            font-family: Tahoma;
            font-size: 11px;
            border-top: 1px solid #999999;
            border-right: 1px solid #999999;
            border-bottom: 1px solid #999999;
            border-left: 1px solid #999999;
            padding-top: 0px;
            padding-right: 0px;
            padding-bottom: 0px;
            padding-left: 0px;
        }
        body {
            margin-left: 5px;
            margin-top: 5px; 
            margin-right: 0px;
            margin-bottom: 10px;
            table {
            border: thin solid #000000;
        }
        -->
        </style>
        </head>
        <body>
        <table width='100%'>
        <tr bgcolor='#CCCCCC'>
        <td colspan='7' height='25' align='center'>
        <font face='tahoma' color='#003399' size='4'><strong>離職處理狀態</strong></font>
        </td>
        </tr>
        </table>
"

Add-Content $ServiceReport $Header
Add-Content $DeleteReport $Header

$TableHeader = "
 <table width='100%'><tbody>
    <tr bgcolor=#CCCCCC>
    <td width='15%' align='center'>賬戶</td>
    <td width='25%' align='center'>應用</td>
    <td width='25%' align='center'>狀態</td>
    </tr>
"

Add-Content $ServiceReport $TableHeader
Add-Content $DeleteReport $TableHeader

#查詢SharePoint入職開通應用中的Item信息
$SPWeb = Get-SPWeb -Identity http://sp.domain.cn
$SPList = $SPWeb.GetList("/Lists/List7")
#定義郵件通知函數
Function Send-Message ($Creater,$ServiceReport)
{
$SmtpClient = New-Object System.Net.Mail.SmtpClient
$SmtpClient.UseDefaultCredentials = $False
$SmtpClient.Credentials = New-Object System.Net.NetworkCredential("[email protected]","P@ssw0rd")
$SmtpClient.Host = "mail.domain.cn"
$MailMessage = New-Object System.Net.Mail.MailMessage
$MailMessage.From = "[email protected]"
$MailMessage.To.Add("[email protected]")
$Mailmessage.CC.Add($Creater)
$MailMessage.Subject = "離職處理報告"
$MailMessage.IsBodyHtml = $True
$MailMessage.Body = Get-Content $ServiceReport
$SmtpClient.Send($MailMessage)
}
Function Send-AdminMessage
{
$SmtpClient = New-Object System.Net.Mail.SmtpClient
$SmtpClient.UseDefaultCredentials = $False
$SmtpClient.Credentials = New-Object System.Net.NetworkCredential("[email protected]","P@ssw0rd")
$SmtpClient.Host = "mail.domain.cn"
$MailMessage = New-Object System.Net.Mail.MailMessage
$MailMessage.From = "[email protected]"
$MailMessage.To.Add("[email protected]")
$MailMessage.Subject = "賬戶刪除報告"
$MailMessage.IsBodyHtml = $True
$MailMessage.Body = Get-Content $DeleteReport
$SmtpClient.Send($MailMessage)
}

#定義空數組用於存儲禁用狀態
$FormatEnumerationLimit = -1
$UserReport = @()
$Recipients = @()
$DeleteResult = @()
#遍歷SharePoint入職開通頁面上的所有Item

Foreach($UserInfo in $SPList.Items)
{
#$UserInfo.GetFormattedValue("員工賬號") -match "sip='(?<Account>[\w\W]*)' id"
#$Account = $Matches.Account.Split("@")[0]
$DisplayName = $UserInfo["員工賬號"].Split("#")[1]
$Account = (Get-ADUser -Filter {DisplayName -eq $DisplayName}).SamAccountName

$User = @()
$User +=[PSCustomObject]@{
Account = $Account
DismDate = $UserInfo["離職日期"]
Company = $UserInfo["公司"]
Approve = $UserInfo.Workflows.StatusText
Disabled = $UserInfo["禁用狀態"]
Deleted = $UserInfo["刪除狀態"]
Creater = $UserInfo["創建者"].Split("#")[1]
}
if($User.Approve -eq "已批準" -and $User.Disabled -eq $False -and (Get-Date) -ge $User.DismDate -and (Get-Date) -lt $User.DismDate.AddDays(30))
{
$Creater = $User.Creater
$Recipients += (Get-ADUser -Filter {DisplayName -eq $Creater } -Properties EmailAddress ).EmailAddress
Try
{
Get-ADUser -Identity $User.Account -Properties * | fl |Out-File -FilePath "C:\Scripts\AutoDismission\$($User.Account)-$(Get-Date -Format "yyyyMMdd").Txt"
Disable-ADAccount -Identity $User.Account -ErrorAction Stop
Switch($User.Company)
{"A"{$OU = "OU=_Disabled,OU=A,DC=domain,DC=cn"}
"B"{$OU = "OU=_Disabled,OU=B,DC=domain,DC=cn"}}
Move-ADObject -Identity $(Get-ADUser $User.Account) -TargetPath $OU
$UserReport += [PSCustomObject]@{
賬戶= $User.Account
應用 = "AD賬號"
狀態 = "已停用"
}
#移除部門組
$Group = (Get-ADUser -Identity $User.Account -Properties MemberOf ).MemberOf | Get-ADGroup
$Group | Remove-ADGroupMember -Members $User.Account -Confirm:$False

#嘗試隱藏郵箱
Try{
Set-Mailbox -Identity $User.Account -HiddenFromAddressListsEnabled $True
$UserReport += [PSCustomObject]@{
賬戶= $User.Account
應用 = "Exchange郵箱"
狀態 = "已停用"
}
}
Catch{
$UserReport += [PSCustomObject]@{
賬戶= $User.Account
應用 = "Exchange郵箱"
狀態 = "禁用失敗"
}
}
#嘗試禁用Lync
Try{
Disable-CsUser -Identity $User.Account -Confirm:$False -ErrorAction Stop
$UserReport += [PSCustomObject]@{
賬戶= $User.Account
應用 = "Lync賬號"
狀態 = "已停用"
}
}
Catch{
$UserReport += [PSCustomObject]@{
賬戶= $User.Account
應用 = "Lync賬號"
狀態 = "禁用失敗"
}
}
#更新禁用信息
$UserInfo["禁用狀態"] = $True
$UserInfo.Update()
}
Catch
{
$UserReport += [PSCustomObject]@{
賬戶= $User.Account
應用 = "AD賬號"
狀態 = "禁用失敗,請檢查賬戶信息"
}
}
}
elseif($User.Approve -eq "已批準" -and $User.Disabled -eq $True -and $User.Deleted -eq $False -and (Get-Date) -ge $User.DismDate.AddDays("30"))
{
$Profiles = $UserProfileManager.GetEnumerator()
$DismUserProfile = $Profiles | Where-Object {$_.MultiloginAccounts -eq "domain\$($User.Account)"}
#刪除SharePoint個人站點
if($DismUserProfile.PersonalSite -ne $Null)
{
Try {
$DismUserProfile.PersonalSite.Delete()
$DeleteResult +=[PSCustomObject]@{
賬戶 = $User.Account
應用 = "SharePoint個人站點"
狀態 = $True
}
}
Catch
{
$DeleteResult +=[PSCustomObject]@{
賬戶 = $User.Account
應用 = "SharePoint個人站點"
狀態 = $False
}
}
}
#刪除SharePoint用戶配置文件
if($DismUserProfile -ne $Null)
{
Try
{
$UserProfileManager.RemoveUserProfile("domain\$($User.Account)")
$DeleteResult +=[PSCustomObject]@{
賬戶 = $User.Account
應用 = "SP配置文件"
狀態 = $True
}
}
Catch
{
$DeleteResult +=[PSCustomObject]@{
賬戶 = $User.Account
應用 = "SP配置文件"
狀態 = $False
}
}
}
#刪除SP賬戶
Try{
#$DisplayName = Get-ADUser -Identity $User.Account -Properties DisplayName
$SPUser = Get-SPUser -Web "http://sp.domain.cn" | Where-Object {$_.DisplayName -eq $DisplayName}
Remove-SPUser -Web "http://sp.domain.cn" -Identity $SPUser -ErrorAction Stop -Confirm:$false
$DeleteResult +=[PSCustomObject]@{
賬戶 = $User.Account
應用 = "SharePoint賬號"
狀態 = $True
}
}
Catch
{
$DeleteResult +=[PSCustomObject]@{
賬戶 = $User.Account
應用 = "SharePoint賬號"
狀態 = $False
}
}
#刪除AD賬戶
Try
{
Get-ADUser $User.Account | Remove-ADObject -Recursive -Confirm:$False -ErrorAction Stop
$DeleteResult +=[PSCustomObject]@{
賬戶 = $User.Account
應用 = "AD賬號"
狀態 = $True
}
}
Catch
{
$DeleteResult +=[PSCustomObject]@{
賬戶 = $User.Account
應用 = "AD賬號"
狀態 = $False
}
}
#更新禁用信息
$UserInfo["刪除狀態"] = $True
$UserInfo.Update()
}
}

$DeleteResult | ForEach-Object {
if($_.狀態 -ne $True)
{
$color = $redColor
}
else
{
$color = $whiteColor
}

  $DataRow = "
        <tr>
        <td width='15%'>$($_.賬戶)</td>
        <td width='25%' >$($_.應用)</td>
        <td width='25%' bgcolor=`'$color`' align='center'>$($_.狀態)</td>
        </tr>
"
Add-Content $DeleteReport $DataRow;
}
Add-Content $DeleteReport "</body></html>"

if($DeleteResult -ne $Null)
{
Send-AdminMessage
}

#添加開通狀態到報表內容
$UserReport | ForEach-Object {
if($_.狀態 -ne "已停用")
{
$color = $redColor
}
else
{
$color = $whiteColor
}

  $DataRow = "
        <tr>
        <td width='15%'>$($_.賬戶)</td>
        <td width='25%' >$($_.應用)</td>
        <td width='25%' bgcolor=`'$color`' align='center'>$($_.狀態)</td>
        </tr>
"
Add-Content $ServiceReport $DataRow;
}
Add-Content $ServiceReport "</body></html>"

#發送報表
If($UserReport -ne $Null)
{
Send-Message -Creater $Recipients -ServiceReport $ServiceReport
}
#移除會話和文件
Remove-PSSession $ExSession
Remove-PSSession $LyncSession
Remove-Item $ServiceReport
Remove-Item $DeleteReport
差點忘了舉例子:
禁用完成是這個樣子的郵件

技術分享圖片

刪除成功是這個樣子的郵件

技術分享圖片


嗯,整套入離職到此就完整結束了,希望可以減輕各位IT管理員的負擔,至於部門變更的流程麽,由於公司小,暫時不涉及,所以需要各位大神們自己動手了。如果有興趣研究 SCO 自動化的朋友,也可以加我QQ 522236464

SharePoint結合PowerShell建立入離職自動化(四)