Pages

Thursday, March 26, 2015

Release Locked Files using Powershell

In recent times I have been writing lot of PowerShell scripts for number of different things. I believe that we all have been doing that. PowerShell is no doubt a powerful tool for not just for both developers and administrators. Microsoft moving away from features and custom solutions PowerShell is the becoming the elixir for almost everything in SharePoint. In this blog we will see a simple script that will be useful for SharePoint Administrator.
We are would have come across users complaining about file is locked by a user. The user might have edited the file last and left for a vacation and someone else is looking to edit the same file the user will see a message that the file is locked by a user for editing. How do we get lock release?
  1. We could either call the person who has locked it and ask him to close it or
  2. Call our best friend PowerShell to help us out here.
Which one of this is easy? I bet PowerShell because he is a true friend and will never let us down at any cost. Enough of stories let's get to the script.

Add-PSSnapin Microsoft.SharePoint.Powershell
# Get Web URL from User
$webUrl = Read-Host "Enter the Web URL : "
# Get Document Library Name from the user
$listTitle = Read-Host "Enter the Document Library Name :"
# Get the Locked File Name from the user
$fileName = Read-Host "Enter the Locked File Name :"
# Get SPWeb Object
$spWeb = Get-SPWeb $webUrl
# Get the Document Library
$list = $web.Lists.TryGetLISt($listTitle)
# Construct a File URL
$fileurl = $web.Url+"/"+$list.Title+"/" + $fileName
# Get the File Handle
$spFile = $web.GetFile($fileurl)
# Get the user by who had locked the file.
$userId = $spFile.LockedByUser.ID
$user = $web.AllUsers.GetByID($userId)
# We need to Impersonate as the user who had locked the file. Get Web, List and File again as impersonated user
$impSite= New-ObjectMicrosoft.SharePoint.SPSite($web.Url, $user.UserToken);
$impWeb = $impSite.OpenWeb();
$impList = $impWeb.Lists.TryGetList($list.Title)
$impItem = $impList.GetItemById($spFile.Item.ID)
$impFile = $impItem.File
# Release the locked File
$impFile.ReleaseLock($impFile.LockId)