Friday, February 13, 2015

Remove SharePoint Client Side File Lock

We have users who leaves file open on their client PC and locks the file for editing.  These locks stop anyone else from updating the document.  This emulates the behavior of a file in a Windows file system, but since SharePoint isn’t a true file system this is handled in the SharePoint content database.
SharePoint handles these file locks as “Short Term” checkouts on the file.  In PowerShell you can see this type of lock in the file property called “CheckOutType”.  The following script would display the checkout status of a file with the ID of “1” inside the “Documents” library in the site located at http://sharepoint/sites/web

1
2
3
4
$w = Get-SPWeb "http://sharepoint/sites/web"
$l = $w.Lists["Documents"]
$i = $l.GetItemById(1)
Write-Host $i.File.CheckOutStatus

The output would be “ShortTerm” for a file locked for editing by the client.  It would be “LongTerm” if someone checked the file out.  It may be advantageous to be able to override these “Short Term” locks in cases such as when a specific user locks an important file by opening it in Word, but then leaves on vacation.  Since there is no “Check Out” according to the SharePoint user interface there is no easy way for someone to do this.

Luckily there is a way to release this lock from PowerShell.  The script below opens the site while impersonating the user with the lock and then releases the lock their client established.  It accepts three parameters: the url of the site, the name of the list, and the id of the item that is locked.  This script will effectually pull the rug out from under the client and different applications may handle this better than others.  Use good judgment when deciding when this script is appropriate.

1
2
3
4
5
6
7
8
9
10
11
12
13
param (
    [string]$url,
    [string]$list,
    [string]$item
)
$w = get-spweb $url
$l = $w.lists[$list]
$i = $l.GetItemById($item)
$s = New-Object Microsoft.SharePoint.SPSite($w.site.id, $i.File.LockedByUser.UserToken)
$w = $s.OpenWeb($w.id)
$l = $w.lists[$list]
$i = $l.GetItemById($item)
$i.File.ReleaseLock($i.File.LockId)

No comments:

Post a Comment