A few years ago I already wrote about how to approve all pending document in a document library via PowerShell. That time I achieved that using the server side object model of SharePoint. Recently we had a situation, where we were not allowed to log on the server, so we had to do the approval from the client side. To achieve that, I’ve adapted the script to the requirements of the client object model.
Here is the result:
- $url = "http://YourSharePointServer/Web/SubWeb"
- # set path according to your current configuration
- Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
- Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
- # set credentials, if the current credentials would not be appropriate
- #$domain = "YourDomain"
- #$userName = "YourUserName"
- #$pwd = Read-Host -Prompt ("Enter password for $domain\$userName") -AsSecureString
- #$credentials = New-Object System.Net.NetworkCredential($userName, $pwd, $domain);
- $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
- #$ctx.Credentials = $credentials
- $web = $ctx.Web
- function approveItems($listTitle)
- {
- Write-Host Processing $listTitle
- $list = $web.Lists.GetByTitle($listTitle)
- $query = New-Object Microsoft.SharePoint.Client.CamlQuery
- $query.ViewXml = "<View Scope = 'RecursiveAll'><ViewFields><FieldRef Name=\'Name\'/><FieldRef Name=\'_ModerationStatus\'/></ViewFields><Query><Where><Eq><FieldRef Name='_ModerationStatus' /><Value Type='ModStat'>2</Value></Eq></Where></Query></View>"
- $items = $list.GetItems($query)
- $ctx.Load($items)
- $ctx.ExecuteQuery()
- $items | % {
- Write-Host Approving:$_["FileLeafRef"]
- $_["_ModerationStatus"] = 0
- $_.Update()
- # if you have an error "The request uses too many resources", call ExecuteQuery here
- # $ctx.ExecuteQuery()
- }
- $ctx.ExecuteQuery()
- Write-Host —————————
- }
- approveItems "TitleOfYourList"
The script assumes, that your current credentials allow you to perform the approval. If it would be not the case, you can comment out the section with credentials in the script, and read for the password of the user having permission to the task. I don’t suggest storing the password in the script.
If the library contains a lot of items waiting for approval, you may get an error message “The request uses too many resources” (see details here). In this case you should call the ExecuteQuery method in the loop for each item, instead of sending the request in a single batch.
