Force CheckIn File Or Undo CheckOut With PowerShell

Sometimes it is not possible to check-in a file in a library over the file item menu or discarding the CheckOut of the file doesn’t work.
Here is a PowerShell script which checks-in the file or discards the CheckOut.

## CheckIn file or undo CheckOut with PowerShell

# Loading the SharePoint PowerShell Snapin if not already loaded
if ((Get-PsSnapin | ?{$_.Name -eq "Microsoft.SharePoint.PowerShell"})-eq $null)
  $PSSnapin = Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

# define Variables
$targetWeb = "http://myFarmURL/SubWeb"
$targetLibrary = "myDocLib"
$fileName = "myFile.docx"

$myWeb = Get-SPWeb $targetWeb
$myLib = $myWeb.GetFolder($targetLibrary)
$myFile = $myLib.Files | ? {$ -eq $fileName}

# for CheckIn use the following line otherwise comment it out with a #
$myFile.CheckIn("MyCheckIn Comment")
# or to undo the CheckOut use the line below


Welcome To My SharePoint Blog!

Currently working on some posts to get really interesting stuff in here!