HOWTO Remove the Lock on a SharePoint File

A user on one of our SharePoint sites had a file in an Exclusive lock on their laptop, and couldn’t remove the lock. After checking a few sites for how to unlock:

http://sharepoint.stackexchange.com/questions/122067/release-client-side-lock-by-javascript

I cobbled together this PowerShell function based on that. By default it displays the lock status of a file, and if you use the $unlock parameter it will also unlock the file.

Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
function SPUnlockFile()
 {
 param(
 [Parameter(Mandatory=$True)][string] $webUrl
 ,[Parameter(Mandatory=$True)][string] $fileUrl
 ,[Parameter()][bool] $unlock = $false
 )
#Get Web and File Objects
 $web = Get-SPWeb $WebURL
 $File = $web.GetFile($FileURL)
#Check if File is Checked-out
 if ($File.CheckOutType -ne "None")
 {
 Write-host "File is Checked Out to user: " $File.CheckedOutByUser.LoginName
 Write-host "Checked Out Type: " $File.CheckOutType
 Write-host "Checked Out On: " $File.CheckedOutDate
#To Release from Checkout, Ask the checked out user to Checkin
 #$File.Checkin("Checked in by Administrator")
 #Write-host "File has been Checked-In"
 }
#Check if File is locked
 if ($File.LockId -ne $null)
 {
 Write-host "File is Locked by:" $File.LockedByUser.LoginName
 Write-host "File Lock Type: "$file.LockType
 Write-host "File Locked On: "$file.LockedDate
 Write-host "File Lock Expires on: "$file.LockExpires
 Write-host "File Lock Id: "$file.LockId
if ($unlock)
 {
 Write-Host "Releasing lock..."
 $userId = $file.LockedByUser.ID
 $user = $web.AllUsers.GetByID($userId)
$impSite= New-Object Microsoft.SharePoint.SPSite($web.Url, $user.UserToken); $impWeb = $impSite.OpenWeb(); $impFile = $impweb.GetFile($FileURL)
 $impFile.ReleaseLock($impFile.LockId)
}
 }
 else
 {
 Write-Host "File is unlocked" -foregroundcolor Green
 }
}
#USAGE
 #SPUnlockFile -weburl "http://weburl" -fileUrl "http://fullpathtofileurl"
 -unlock $false
Advertisements

One Response to “HOWTO Remove the Lock on a SharePoint File”

  1. SharePoint file locked/ Checked out when it is not | soumyabhatta Says:

    […] I am an admin and I have access to servers and PowerShell. This Back in the Hack post is the key to resolving this problem. Thanks to gavinmckay: https://gavinmckay.wordpress.com/2015/04/10/howto-remove-the-lock-on-a-sharepoint-file/ […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: