Unlock Documents With PowerShell

One of my users was constantly getting locked out of his own documents. Upon saving a document, he would receive the following error:

The file “filename” is locked for exclusive (or shared) use by “his username””

The issue was that his user only had “contribute” permissions. While that should be enough, he needed “edit” permissions to avoid locking his own documents.

While troubleshooting, I used a PowerShell script that unlocks documents that are locked for shared use.


Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Web and File URLs
$WebURL ="http://twainstlportal.twainfinancial.com/sites/crmdocs/BD"
$FileURL = "http://sp2013/sites/company/filename.docx"

#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 check in
#$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 Loked out 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

#To Release the lock, use:
#$File.ReleaseLock($File.LockId)
#Write-host "Released the lock!"
}

Change the filename to the URL of the locked document. Uncomment line 32 and 33 to unlock the document.