Powershell – Close locked file in Windows Share using Powershell and Openfiles

file-sharingpowershellwindows-server-2008

I work with a lot of folder shares, but there are a bunch of locked files which have been opened by some other process.

I need to close those files. So far I've been using MMC – System Tools – Shared Folders – Open Files.

It would be far more convenient if I could use PowerShell to filter the list/table retrieved by OpenFiles.exe and once I get the file ID close it with net file /close, or some other PS native means to similar effect.

I am new to PowerShell, so I wonder if there is a way to create a PS script that receives the file's path and then used the file ID to close that file?

Best Answer

Get-SmbOpenFile and Close-SmbOpenFile will get the job done for you.

Logged into your file server, start PowerShell. Use Get-SmbOpenFile to display all of the open files on your file server. The files will display along with the following table headers

FileId                  SessionId               Path           ShareRelativePath      ClientComputerName     ClientUserName

Use Close-SmbOpenFile to close a file.

Close-SmbOpenFile -FileId 4415226383589

If you know an Excel file is the issue, you can narrow your search for all open files with a .XLSX extension.

Get-SmbOpenFile | Where-Object -Property sharerelativepath -match ".XLSX"

After finding your problem file in the results, you can then close the file by the fileID.

If you want to close all open files on your file server:

Get-SmbOpenFile | Close-SmbOpenFile

If you want to close one or more files that are open and that match the file extension ".XLSX".

Get-SmbOpenFile | Where-Object -Property sharerelativepath -match ".XLSX" | Close-SmbOpenFile -Force

****NOTE**** Per the TechNet article "The Close-SMBOpenFile cmdlet forcibly closes a file that is open by one of the clients of the Server Message Block (SMB) server. This cmdlet should be used with care as it may result in data loss to the client for which the file is being closed if the client has not flushed all of the file modifications back to the server before the file is closed."

For more information on the CMDlets

Get-SmbOpenFile https://technet.microsoft.com/en-us/library/jj635701(v=wps.620).aspx

Close-SmbOpenFile https://technet.microsoft.com/en-us/library/jj635721(v=wps.620).aspx