Clear short term file lock in SharePoint 2013+ - Fabian Neve

About SharePoint, Javascript, PowerShell, and other technical stuff

Friday, February 9, 2018

Clear short term file lock in SharePoint 2013+

If a file is locked by a user who doesn't work on it anymore (he closed the file already more than 10 minutes ago) it can happen that the file is still locked.



Here a script to unlock the file:

$web = get-spweb "https://domain/sitecollection/site"
$list = $web.Lists["Documents"]
$item = $list.Items.GetItemById(123)
$item.File.ReleaseLock($item.File.LockId)
$web.Dispose()

If you get an error like:

Exception calling "ReleaseLock" with "1" argument(s): "The file filename.xlsx is locked for exclusive use by DOMAIN\user"

...then try next script to use impersonation. This happens when a user left the file open and nobody else is able to edit the file in his absence.

$web = get-spweb "https://domain/sitecollection/site"
$list = $web.Lists["Documents"]
$item = $list.Items.GetItemById(123)
$userId = $item.File.LockedByUser.ID
$user = $web.AllUsers.GetById($userId)
$impSite = New-Object Microsoft.SharePoint.SPSite($web.Url, $user.UserToken);
$impWeb = $impSite.OpenWeb();
$impList = $impWeb.Lists[$list.Title];
$impItem = $impList.GetItemById($item.ID);
$impItem.File.ReleaseLock($impItem.File.LockId)
$impWeb.Dispose()
$impSite.Dispose()
$web.Dispose()

Found those great and absolutetly useful scripts at Stackexchange where you get more informations about short term file lock.

No comments:

Post a Comment