[玩转系统] 文档过期监视器 - 使用 PowerShell 脚本实现自动化
作者:精品下载站 日期:2024-12-14 13:42:21 浏览:12 分类:玩电脑
文档过期监视器 - 使用 PowerShell 脚本实现自动化
要求:有一堆文档库,其中有多个文档加载在各种网站集中。我们必须根据一列监控其到期日期,并向 SharePoint 组的所有成员发送电子邮件通知。此外,所有发送的电子邮件都应记录在跟踪列表中。
解决方案:让我们编写一个PowerShell脚本来扫描所需的文档库并发送电子邮件。顺便说一句 - 适用于 MOSS 2007(当然,该脚本适用于任何 SharePoint 版本!)
基于日期列监视文档过期的 PowerShell 脚本:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
##################################################################################
## VARIABLES SECTION ##
##################################################################################
$LibraryURLs = @("https://intranet.Crescent.com/sites/IT/docs/", "https://intranet.Crescent.com/sites/operations/inventory/", "https://intranet.Crescent.com/sites/Sales/documents")
### Variables for Email setup
#URL of the Site where the SharePoint group exists
$EmailGroupSite = "https://intranet.Crescent.com/sites/IT/"
#Name of the SharePoint Group to which emails to be sent
$EmailGroupName= "Report Group"
#Internal Name of the Column which stores the expiration date of documents
$ExpiryDateColumnInternalName = "Expiration_x0020_Date0"
#How to get the Internal name of a SharePoint Column?
#Refer https://www.sharepointdiary.com/2011/06/sharepoint-field-display-name-vs-internal-name.html
#Site URL where the tracking list "Document Expiration Monitor - Tracking" to be maintained
$TrackingSiteURL = "https://intranet.Crescent.com/sites/IT/"
$ExpiryDays = 7
$SMTPServer = "smtp.Crescent.com"
$EmailFrom = "[email protected]"
$EmailSubject = "Document Expiration Monitor Report as on $(Get-Date)"
#Region Functions
###############################################################################
## FUNCTIONS ##
###############################################################################
#Functions for Get-SPSite & Get-Web in MOSS 2007
function global:Get-SPSite($url) {
return new-Object Microsoft.SharePoint.SPSite($url)
}
function global:Get-SPWeb($url) {
$site= New-Object Microsoft.SharePoint.SPSite($url)
if($site -ne $null) {
$web=$site.OpenWeb();
}
return $web
}
#Validate the Web at given URL
function Validate-Web($WebURL)
{
try {
$web = Get-SPWeb $WebURL
return $web
}
catch {
$Message = "Error in Site URL:$WebURL. Please provide valid Site URL!"
Write-Host $Message -ForegroundColor red
Append-LogMessage $Message $error[0]
#Continue executing code
continue
return $null
}
}
#Validate the Web at given URL
function Validate-SPSite($SiteURL)
{
try {
$Site = Get-SPSite $SiteURL
return $Site
}
catch {
$Message = "Error in Site Collection URL:$SiteURL."
Write-Host $Message -ForegroundColor red
Append-LogMessage $Message $error[0]
#Continue executing code
continue
return $null
}
}
#Function to validate given List URL
function Validate-List($ListURL)
{
try {
$list = $web.GetList($ListURL)
return $list
}
catch {
$Message = "Error in List URL: $ListURL! Please provide valid List URL!"
Write-Host $Message -ForegroundColor red
Append-LogMessage $Message $error[0]
#Continue executing code
continue
return $null
}
}
function Send-Email ($EMailBody, $EmailTo) {
try {
#Send the Mail
$MailMessageParameters = @{
SmtpServer = $SMTPServer
Subject = $EmailSubject
Body = $EmailBody
From = $EmailFrom
To = $EmailTo
}
Send-MailMessage @MailMessageParameters -BodyAsHtml
Append-LogMessage "Email has been sent to :"$EmailTo
}
catch {
Write-Host "Error sending email, Please check log file!" -ForegroundColor Red
Append-LogMessage $error[0]
}
}
#Function to Get the Location where script is located
function GetScriptDir
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
return Split-Path $Invocation.MyCommand.Path
}
#Extract Emails from each user in a Group
function Get-GroupEmails()
{
try {
$Emails=@()
$Site = Validate-SPSite $EmailGroupSite
if($site -ne $null)
{
$Group = $site.RootWeb.sitegroups | Where {$_.Name -match $EmailGroupName}
#$Group= $web.SiteGroups[$GroupName]
if($Group -ne $null)
{
$Users = $Group.Users
foreach ($User in $Users)
{
if( ($user.Email -ne [string]::IsNullOrEmpty()) -and ($user.Email -ne $null) )
{
$Emails+=$user.Email
}
}
$Emails = $Emails -split ","
return $Emails
}
else
{
$Message = "E-mail Group Name:$EmailGroupName Not found!"
Write-Host $Message -ForegroundColor red
Append-LogMessage $Message $error[0]
return $null
}
}
}
catch {
$Message = "Error in Get-GroupEmails Function!"
Write-Host $Message -ForegroundColor red
Append-LogMessage $Message $error[0]
#Continue executing code
continue
return $null
}
}
#Function to Log details to Tracking List
function LogTo-TrackingList($EmailBody)
{
$web = Validate-Web $TrackingSiteURL
if($web -eq $null)
{
# Creating base file to append to, adding a new line for readability
$Message = "Tracking Site URL is not valid!"
Write-Host $Message -ForegroundColor Red
Append-LogMessage $Message
return
}
#Try to Get the "Tracking List"
$TrackingList = $web.Lists | Where { $_.Title -match "Document Expiration Monitor - Tracking"}
#If Tracking list doesnt exist, Create it
if($TrackingList -eq $null)
{
#Create New Tracking List
$TrackingListID = $Web.Lists.Add("DEMTracking","List to Track Document Expiration Monitor Mails",[Microsoft.SharePoint.SPListTemplateType]::GenericList)
#Set Name for the List
$TrackingList = $web.Lists[$TrackingListID]
$TrackingList.Title="Document Expiration Monitor - Tracking"
$TrackingList.update()
#Rename the "Title Field" to Tracking ID
$TitleField = $TrackingList.Fields.GetFieldByInternalName("Title")
#Set Field Display Name and Update
$TitleField.Title ="Tracking Date"
$TitleField.Update()
#Add Email Body Field
$EmailBodyField = $TrackingList.Fields.Add("Email Body","Note",$true)
$trackingList.Fields["Email Body"].RichText = $True
$trackingList.Fields["Email Body"].RichTextMode = "FullHtml"
$trackingList.Fields["Email Body"].update()
}
#Add New Item to Tracking List
$item = $TrackingList.Items.Add()
#Set the Tracking Date & Email Body field values
$item["Email Body"] = $EmailBody
#Set the Tracking Date field
$item["Tracking Date"] = $TodaysDate
$item.update()
#Log details to Tracking List
$web.dispose()
}
# Appends text to the log message
function Append-LogMessage($text)
{
Add-Content $LogTextFileName $text"`r" -Encoding UTF8
}
#EndRegion
#Variables for Internal processing
$ScriptPath = GetScriptdir
#Get the Template HTM File with CSS
$MailContent = Get-Content -Path "$ScriptPath\template.htm" -Encoding UTF7 | Out-String
$CAMLDateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
$DateFormat = "MM/dd/yyyy"
$TodaysDate = Get-date
$TodaysDateFormatted = (Get-date).ToString($CAMLDateFormat)
$ExpirationDate = (Get-Date).AddDays($ExpiryDays)
$ExpirationDateFormatted = (Get-Date).AddDays($ExpiryDays).ToString($CAMLDateFormat)
$LogTextFileName = "$ScriptPath\DEM_LOG.txt"
$Message =""
# Creating base file to append to, adding a new line for readability
$Message = "Script Execution Started at $TodaysDate." >> $LogTextFileName
Write-Host $Message -ForegroundColor DarkGreen
Append-LogMessage $Message
###############################################################################
## PROCESS EACH DOCUMENT LIBRARY AND SEND EMAIL ##
###############################################################################
########## Process "Expiring Documents" ###########
$MailContent+= "<h2> Document Expiry Monitor - Report as on : $(Get-Date) </h2>"
$ExpiringContentHeader = "<h3 style='color: #333399;'> List of Expiring Documents: </h3> <table class='altrowstable' cellpadding='5px' cellspacing='5'><tr><th>Document Name </th><th>Created By</th><th>Created on</th><th> Expiry Date </th><th> URL </th></tr>"
$MailContent += $ExpiringContentHeader
$ExpiringContent=""
$ExpiredContent=""
# Loop through items and Get all Expiring Documents
foreach ($ListURL in $LibraryURLs)
{
#Get the web
$web = Validate-Web $ListURL
if($web -eq $null) {
#Skip the current list and proceed with the next from array
continue
}
#Get the List
$list = Validate-List $ListURL
if($list -eq $null) {
#Skip the current list and proceed with the next from array
continue
}
#Check if the list has the "Expiration Date" Column
if ($list.Fields.GetFieldByInternalName($ExpiryDateColumnInternalName) -eq $false)
{
$Message = "$ListURL does not contains Expiration Date Field specified!"
Write-Host $Message -ForegroundColor red
Append-LogMessage $Message
#Skip the current list and proceed with the next from array
continue
}
# Write out the dates we're looking for
$Message = "Searching $ListURL for Expiring documents with Expiration Date between " + $TodaysDate + " - " + $ExpirationDate
Write-Host $Message -ForegroundColor DarkGreen
Append-LogMessage $Message
# Get all Expiring Documents
$ExpiringQuery = '<Where><And><Geq><FieldRef Name="' + $ExpiryDateColumnInternalName + '" /><Value Type="DateTime" IncludeTimeValue="True">' + $TodaysDateFormatted +
'</Value></Geq><Leq><FieldRef Name="' + $ExpiryDateColumnInternalName + '" /><Value Type="DateTime" IncludeTimeValue="True">' + $ExpirationDateFormatted + '</Value></Leq></And></Where>'
$SPExpiringQuery = new-object Microsoft.SharePoint.SPQuery
$SPExpiringQuery.ViewAttributes = "Scope='Recursive'"
$SPExpiringQuery.Query = $ExpiringQuery
$ExpiringListItems = $List.GetItems($SPExpiringQuery)
$Message = "Found " + $ExpiringListItems.Count + " Expired document(s)."
Write-Host $Message -ForegroundColor DarkGreen
Append-LogMessage $Message
#If There are some expiring documents found
if($ExpiringListItems.Count -gt 0)
{
foreach($Item in $ExpiringListItems)
{
$ExpiringContent+= "<tr> <td> $($item.Name) </td> <td> $($item.File.Author.Name) </td> <td> $($item.File.TimeCreated.ToString($DateFormat)) </td> <td> $($Item
[$ExpiryDateColumnInternalName].ToString($DateFormat)) </td> <td> <a href='$($web.URL)/$($item.URL)'>$($web.URL)/$($item.URL)</a> </td> </tr>"
}
}
}
if($ExpiringContent.Length -eq 0)
{
$ExpiringContent+= "<tr> <td colspan=5> No Expiring Documents Found! </td> </tr>"
}
$ExpiringContent+= "</table><br/>"
$MailContent += $ExpiringContent
########## Process "Expired Documents " ###########
$ExpiredContentHeader = "<h3 style='color: #660033;'> List of Expired Documents: </h3> <table class='altrowstable' cellpadding='5px' cellspacing='5'><tr><th>Document Name </th><th>Created
By</th><th>Created on</th><th> Expiry Date </th><th> URL </th></tr>"
$MailContent += $ExpiredContentHeader
$ExpiredContent=""
# Loop through items and Get all Expired Documents
foreach ($ListURL in $LibraryURLs)
{
if($web -eq $null) {
#Skip the current list and proceed with the next from array
continue
}
#Get the List
$list = Validate-List $ListURL
if($list -eq $null) {
#Skip the current list and proceed with the next from array
continue
}
#Check if the list has the "Expiration Date" Column
if ($list.Fields.GetFieldByInternalName($ExpiryDateColumnInternalName) -eq $false)
{
$Message = "$ListURL does not contains Expiration Date Field specified!"
Write-Host $Message -ForegroundColor red
Append-LogMessage $Message
#Skip the current list and proceed with the next from array
continue
}
# Write out the dates we're looking for
$Message = "Searching $ListURL for Expired documents with Expiration Date between " + $TodaysDate + " - " + $ExpirationDate
Write-Host $Message -ForegroundColor DarkGreen
Append-LogMessage $Message
# Get all Expired Documents
$ExpiredQuery = '<Where><Lt><FieldRef Name="' + $ExpiryDateColumnInternalName + '" /><Value Type="DateTime" IncludeTimeValue="True">' + $TodaysDateFormatted + '</Value></Lt></Where>'
$SPExpiredQuery = new-object Microsoft.SharePoint.SPQuery
$SPExpiredQuery.ViewAttributes = "Scope='Recursive'"
$SPExpiredQuery.Query = $ExpiredQuery
$ExpiredListItems = $List.GetItems($SPExpiredQuery)
$Message = "Found " + $ExpiredListItems.Count + " Expired document(s)."
Write-Host $Message -ForegroundColor DarkGreen
Append-LogMessage $Message
#If There are some expired documents found
if($ExpiredListItems.Count -gt 0)
{
foreach($Item in $ExpiredListItems)
{
$ExpiredContent+= "<tr> <td> $($item.Name) </td> <td> $($item.File.Author.Name) </td> <td> $($item.File.TimeCreated.ToString($DateFormat)) </td> <td> $($Item
[$ExpiryDateColumnInternalName].ToString($DateFormat)) </td> <td> <a href='$($web.URL)/$($item.URL)'>$($web.URL)/$($item.URL)</a> </td> </tr>"
}
}
}
if($ExpiredContent.Length -eq 0)
{
$ExpiredContent+= "<tr> <td colspan=5> No Expired Documents Found! </td> </tr>"
}
$ExpiredContent+= "</table><br/>"
$MailContent += $ExpiredContent
$MailContent += "</body></html>"
#Email the Body
$EmailAddresses = Get-GroupEmails
if($EmailAddresses -ne $null)
{
Send-Email $MailContent $EmailAddresses
}
#Log to Tracking table
LogTo-TrackingList $MailContent
###############################################################################
## CLEAN UP ##
###############################################################################
# Log end of processing
$Message = "Finished Processing Document Expiration Monitor Script by $(Get-Date)."
Write-Host $Message -ForegroundColor DarkGreen
Append-LogMessage $Message
# Dispose of the web object
$web.Dispose()
Template.htm 文件内容:
<html>
<head>
<!-- CSS goes in the document HEAD or added to your external stylesheet -->
<style type="text/css">
body{
font-family: Calibri;
height: 12pt;
}
table.altrowstable {
border-collapse: collapse;
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #a9c6c9;
border: b1a0c7 0.5pt solid;
}
table.altrowstable th {
border-width: 1px;
padding: 5px;
background-color:#8064a2;
border: #b1a0c7 0.5pt solid;
font-family: Calibri;
height: 15pt;
color: white;
font-size: 11pt;
font-weight: 700;
text-decoration: none;
}
table.altrowstable td {
border: #b1a0c7 0.5pt solid; font-family: Calibri; height: 15pt; color: black; font-size: 11pt; font-weight: 400; text-decoration: none;
}
</style>
</head>
<body>
实际的 PowerShell 脚本:
跟踪列表:
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag