Администратор файлового сервера Windows может вывести список открытых файлов в общей сетевой папке и принудительно закрыть заблокированные файлы, открытые пользователями в монопольном режиме. Если пользователь открыт файл в общей сетевой SMB папке на сервере на чтение и запись и забыл его закрыть (ушел домой, в отпуск), другие пользователи не смогут внести изменения в файл.
В этой статье мы рассмотрим, как получить список открытых файлов на файловом сервере Windows и пользователей, которые их используют, а также способы сброса файловых сессий для разблокировки открытых файлов.
Содержание:
- Вывод списка открытых файлов в сетевой папке Windows
- Кто открыл файл в общей сетевой папке на сервере Windows?
- Принудительно закрыть открытый файл на сервере Windows
- Как удаленно закрыть открытые по сети файлы с помощью PowerShell?
Вывод списка открытых файлов в сетевой папке Windows
Список открытых по сети файлов в Windows можно получить с помощью графической консоли Computer Management (Управление компьютером).
- Откройте консоль
compmgmt.msc
и перейдите в раздел System Tools -> Shared Folders -> Open files (Служебные программы -> Общие папки -> Открыты файлы); - В правой части окна отображается список открытых файлов. Здесь указаны локальный путь к файлу, имя учетной записи пользователя, количество блокировок и режим, в котором открыт файл (Read или Write+Read).
Также вы можете вывести список открытых на сервере файлов из командной строки:
Openfiles /Query /fo csv
Команда возвращает номер сессии, имя пользователя, количество блокировок и полный путь к файлу.
Cо списком открытых файлов на сервере удобнее работать с помощью PowerShell командлета Get-SmbOpenFile:
Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID
В выводе команда содержится имя пользователя, имя (IP адрес) удаленного компьютера, с которого открыт файл), имя файла и ID файловой сессии.
Кто открыл файл в общей сетевой папке на сервере Windows?
Чтобы удаленно определить пользователя, который открыл (заблокировал) файл cons.adm в сетевой папке на сервере mskfs01, выполните команду:
Openfiles /Query /s mskfs01 /fo csv | find /i "cons.adm"
Ключ /i используется, чтобы выполнялся поиск без учета регистра в имени файла.
Можно указать только часть имени файла. Например, чтобы узнать, кто открыл xlsx файл, в имени которого есть строка farm, воспользуйтесь таким конвейером:
Openfiles /Query /s mskfs01 /fo csv | find /i "farm"| find /i "xlsx"
С помощью PowerShell также можно получить информацию о пользователе, который открыл файл. Например:
Вывести все открытые по сети exe файлы:
Get-SmbOpenFile | Where-Object {$_.Path -Like "*.exe*"}
Найти открытые файлы по части имени:
Get-SmbOpenFile | Where-Object {$_.Path -Like "*защита*"}
Вывести все файлы, открытые определенным пользователем:
Get-SMBOpenFile –ClientUserName "corp\aaivanov" |select ClientComputerName,Path
Найти файлы, которые открыли с указанного компьютера:
Get-SMBOpenFile –ClientComputerName 192.168.12.170| select ClientUserName,Path
Принудительно закрыть открытый файл на сервере Windows
Можно закрыть открытый файл через консоль Computer Management. Найдите файл в списке секции Open Files, выберите в контекстном меню пункт “Close Open File”.
Если на сервере по сети открыты сотни файлов, то найти нужный файл в графической консоли довольно сложно. Лучше использовать инструменты командной строки.
Закрыть файл можно, указав ID его SMB сессии. Получить ID сессии файла:
Openfiles /Query /fo csv | find /i "report2023.xlsx"
Теперь можно принудительно отключить пользователя по полученному идентификатору SMB сессии:
Openfiles /Disconnect /ID 3489847304
SUCCESS: The connection to the open file "D:\path\REPORT2023.XLSX" has been terminated.
Вы разблокировали открытый файл и теперь его могут открыть другие пользователи.
Можно принудительно сбросить все сессии и освободить все файлы, открытые определённым пользователем:
openfiles /disconnect /s mskfs01 /u corp\aivanova /id *
Можно закрыть открытый файл по ID сессии с помощью PowerShell командлета Close-SmbOpenFile.
Close-SmbOpenFile - SessionId 3489847304
Найти и закрыть открытый файл одной командой:
Get-SmbOpenFile | where {$_.Path –like "*report2023.xlsx"} | Close-SmbOpenFile
Для подтверждения сброса сессии и освобождения отрытого файла нажмите
Y
->
Enter
.
Чтобы закрыть файл без предупреждения, добавьте параметр
-Force
в последнюю команду.
С помощью Out-GridView можно сделать простую графическую форму для поиска и закрытия файлов. Следующий скрипт выведет список открытых файлов. Администратору нужно с помощью фильтров в таблице Out-GridView найти и выделить нужные файлы, а затем нажать ОК. В результате выбранные файлы будут принудительно закрыты.
Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID| Out-GridView -PassThru –title “Select Open Files”|Close-SmbOpenFile -Confirm:$false -Verbose
Принудительное закрытие открытого файла на файловом сервере, вызывает потерю несохраненных пользователем данных. Поэтому команды openfiles /disconnect и
Close-SMBOpenFile
нужно использовать с осторожностью.
Как удаленно закрыть открытые по сети файлы с помощью PowerShell?
Командлеты Get-SMBOpenFile и Close-SmbOpenFile можно использовать чтобы удаленно найти и закрыть открытые файлы. Сначала нужно подключиться к удаленному SMB серверу Windows через CIM сессию:
$sessn = New-CIMSession –Computername mskfs01
Также вы можете подключаться к удаленному серверам для запуска команд через командлеты PSRemoting: Enter-PSSession или Invoke-Command .
Следующая команда найдет сессию для открытого файла
*pubs.docx
и завершит ее.
Get-SMBOpenFile -CIMSession $sessn | where {$_.Path –like "*pubs.docx"} | Close-SMBOpenFile -CIMSession $sessn
Подтвердите закрытие файла, нажав
Y
. В результате вы разблокировали открытый файл. Теперь его могут открыть другие пользователи.
С помощью PowerShell вы можете закрыть и осведомить на файловом сервере все файлы, открытые определенным пользователем (пользователь ушел домой и не освободил файлы). Например, чтобы сбросить все файловые сессии для пользователя ipivanov, выполните:
Get-SMBOpenFile -CIMSession $sessn | where {$_.ClientUserName –like "*ipivanov*"}|Close-SMBOpenFile -CIMSession $sessn
If you’re poking through a modern Windows Server OS such as 2016, 2019, or 2022 and wondering where the Share and Storage Management went then you’re not alone.
Most people hunting for open files in Windows Server instinctively go to Share and Storage Management since that’s where you found things like that in days past.
Since at least Server 2008 Microsoft has introduced Open File management via the Computer Management and slowly phased out the Share and Storage Management, which is now completely absent in Server 2016 forward.
How to View Open Files in Computer Management
The easiest way to see what shared folders and files are open on your system (or a remote system) is to use Computer Management.
- Right click your start menu button and click on Computer Management. You can also search for Computer Management or Compmgmt.msc in your start menu.
- Expand System Tools -> Shared Folders -> Open Files
You will now see a list of all the open directories and files by other users on your server. If you need to close any of these files so they aren’t locked anymore (for copying, deleting, updating, etc…) just right click on any of the files or folder and click Close.
If you are using DFS Namespace with a lot of file servers, I’ve found it handy to keep an MMC console configured with all of my file servers Share Folder views. This way I can jump back and forth between them quickly when I need to kill an open file. You can even set up the MMC console to only show Open Files for each of your servers as seen below:
How to View Open Files in Resource Monitor
Another easy way to view files that are open on a system is to use the Resource Monitor. If you’ve never used the Resource Monitor I highly recommend poking around in it a bit. It’s a pretty powerful tool that ships with Windows and is greatly underutilized by most (in my opinion).
- Search for Resource Monitor in your start menu and click on it.
- When the Resource Monitor Opens click Monitor -> Stop Monitoring
- Expand Disk Activity to view a list of processes and the associated Open File location.
The drawback to using the Resource Monitor to view Open Files is you cannot close the open files. It does at least tell you where they are located.
If you need to close an open file or a file locked by a system process on Windows 10 or Windows 11 you can use free tools such as IOBit Unlocker.
Once the software is installed you just need to right click on the file or directory that is locked (which you can find using one of the methods above) and click on IOBit Unlocker in the context menu.
You’ll be presented with a screen similar to below that will show selected Files/Folders, what processes are locking them, and a button to perform the unlocking of the file.
It doesn’t get much simpler than that.
Recommended Tool: ManageEngine OpManager
- Multi-vendor Network Monitoring
- Simple Installation & Setup
- Intuitive UI
- Complete Visibility
- Intelligent Detections
- Easy Resolutions
Network Engineer III
I am a Senior Network Engineer who has spent the last decade elbow deep in enterprise System Administration and Networking in the local government and energy sectors. I can usually be found trying to warm up behind the storage arrays in the datacenter.
A Windows file server admin can list the files that are open in a shared folder and force locked files to close. If a user opens a file in a shared SMB folder on the file server for writing and forgets to close it, this means that other users won’t be able to modify the file.
In this article, we’ll look at how to get a list of the files that are open on a Windows file server, the users that are using them, and how to reset file sessions to unlock open files.
Contents:
- View Open Files on Windows Server
- How to See Who Has Locked an Open File on Windows
- Close Open Files on Windows Server
- How to Remotely Close Open Files with PowerShell
View Open Files on Windows Server
You can use the graphical Computer Management snap-in to get a list of files open over the network in Windows
- Run the
compmgmt.msc
console and go to System Tools -> Shared Folders -> Open files; - A list of open files is displayed on the right side of the window. Each entry shows the local path to the file, the user account name, the number of locks, and the mode in which the file is opened (Read or Write+Read).
You can also list the files open on the server from the command line:
openfiles /Query /fo csv
The command returns the session number, user name, number of locks, and the full local path to the file.
A more convenient way to work with the list of files that are open on the server is to use the Get-SmbOpenFile PowerShell cmdlet:
Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID
The command output includes the user name, the name (IP address) of the remote computer from which the file was opened, the file name, and the SMB session ID.
How to See Who Has Locked an Open File on Windows
Users will see a warning if they try to open a locked file.
The document filename is locked for editing by another user. To open a read-only copy of his document, click…
To remotely identify the user who has locked the name.docx file in a shared folder on the lon-fs01 server, run the command
openfiles /query /s lon-fs01 /fo csv | find /i "name.docx"
The /i
switch is used to make the filename case insensitive when searching.
You can only specify part of the filename. For example, to find out who has opened a .XLSX file that contains the string sale_report in its name, use the following pipe:
openfiles /Query /s lon-fs01 /fo csv | find /i "sale_report"| find /i "xlsx"
To get information about the user who opened the file, you can also use PowerShell.
List all EXE files opened from the shared folder:
Get-SmbOpenFile | Where-Object {$_.Path -Like "*.exe*"}
Search for open files by part of their name:
Get-SmbOpenFile | Where-Object {$_.Path -Like "*reports*"}
List all files opened by a specific user:
Get-SMBOpenFile –ClientUserName "corp\mjenny"|select ClientComputerName,Path
Find files opened from a specified remote computer:
Get-SMBOpenFile –ClientComputerName 192.168.1.190| select ClientUserName,Path
Close Open Files on Windows Server
You can use the Computer Management console to close an open file. Locate the file in the list in the Open Files section and select ‘Close Open File’ from the menu.
Finding the file you want in the graphical console can be difficult when there are hundreds of files open on the server. It’s better to use command line tools in this case.
You can close a file by specifying its SMB session ID. Get file session ID:
Openfiles /Query /fo csv | find /i "report2023.xlsx"
The received SMB session ID can now be used to force a user to disconnect:
openfiles /disconnect /ID 3489847304
SUCCESS: The connection to the open file "D:\docs\public\REPORT2023.XLSX" has been terminated.
If you want to forcibly reset all sessions and release all files opened by a specific user:
openfiles /disconnect /s lon-fs01/u corp\mjenny /id *
You can use the PowerShell cmdlet Close-SmbOpenFile to close an open file handler by session ID.
Close-SmbOpenFile -FileId 4123426323239
Find and close an open file with a one-line command:
Get-SmbOpenFile | where {$_.Path –like "*annual2020.xlsx"} | Close-SmbOpenFile -Force
To confirm the reset of the session and release the open file, press Y
-> Enter
.
Add the -Force
parameter to the last command to close the file without warning.
The Out-GridView cmdlet allows you to create a simple graphical form for finding and closing open files. The following script will list open files. The administrator must use the filters in the Out-GridView table to find and select the required files, and then click the OK button to forcibly close them.
Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID| Out-GridView -PassThru –title "Select Open Files"|Close-SmbOpenFile -Confirm:$false -Verbose
Note. Forcibly closing a file that is open on a file server will cause the user to lose any unsaved data. So, the openfiles /disconnect
and Close-SMBOpenFile
commands should be used with care.
How to Remotely Close Open Files with PowerShell
The Get-SMBOpenFile
and Close-SmbOpenFile
cmdlets can be used to remotely find and close open (locked) files. The first step is to establish a CIM session with a remote Windows file server:
$sessn = New-CIMSession –Computername lon-fs01
You can also use the PSRemoting cmdlets (Enter-PSSession or Invoke-Command) to connect to a remote server and run commands.
The following command finds and closes the session for the open file pubs.docx.
Get-SMBOpenFile -CIMSession $sessn | where {$_.Path –like "*pubs.docx"} | Close-SMBOpenFile -CIMSession $sessn
Confirm closing of the file by pressing Y
. This unlocks the open file, and other users can open it.
You can use PowerShell to close SMB sessions and unlock all files that a specific user has opened (for example, if a user goes home and doesn’t release the open files.). The following command resets all file sessions of the user mjenny:
Get-SMBOpenFile -CIMSession $sessn | where {$_.ClientUserName –like "*mjenny*"}|Close-SMBOpenFile -CIMSession $sessn
Windows file server administrators often have to force close the shared files that are open simultaneously by multiple users.
Today, let’s see how our Support Engineers view Open Files in Windows server and how we close (reset) file sessions to unlock open files.
View Open Files on a Shared Folder on Windows Server
We can get the list of open files on Windows file server using the built-in Computer Management (
compmgmt.msc
) graphic snap-in.
First, we open the Computer Management console on file server and go to System Tools -> Shared Folders -> Open files. We can see a list of open files on current SMB server on the right side of the window.
The list contains the local path to the file, the name of the user account that opens the file, the number of locks and the mode in which the file is opened (Read or Write+Read).
We can get the same list of open files using the built-in
openfiles.exe
console tool.
For example, using the following command we can get the Session ID, username and full local path to the open file:
openfiles /Query /fo csv |more
When a user remotely access a file in a shared network folder, a new SMB session is created. We can manage open files using these session IDs.
We can display a list of open files on a remote server.
For example, to list all open files in shared folders on the lon-fs01 host we use:
openfiles /Query /s lon-fs01 /fo csv
The openfiles command also allows us to view the list of locally opened files. To view it, we enable the “Maintain Objects List” option using the command:
openfiles /local on
, and reboot the server.
it is recommended to use this mode only for debugging purposes, since it can negatively affect server performance.
[Need assistance to view Open Files? We’d be happy to help]
How to Find Out Who is Locking a File in a Shared Folder?
To identify the user who opened (locked) the filename.docx file on the shared network folder on the remote server lon-fs01, we run the command:
openfiles /Query /s lon-fs01 /fo csv | find /i “filename.docx”
The /i key is to perform case-insensitive file search.
We can specify only a part of the file name.
For example, We need to find out who opened an XLSX file containing “sale_report” in its name. To find, we use the following pipe:
openfiles /Query /s lon-fs01 /fo csv | find /i “sale_report”| find /i “xlsx”
Of course, we can find this file in the Computer Management GUI, but it is less convenient.
How to Forcibly Close an Open File on a SMB Share?
To close an open file, we find it in the list of files in ‘Open File’ section and select ‘Close Open File’ in the context menu.
If there are hundreds of open files on the file server, it will not be easy to find the specific file in the console. It is more convenient to use the Openfiles command line tool.
As we have already mentioned, it returns the session ID of the open file. By using this session ID we can force close the file by resetting the SMB connection.
First, we need to find the session ID of the open file:
openfiles /Query /s lon-fs01 /fo csv | find /i “farm”| find /i “.xlsx”
Disconnect the user from file using the received SMB session ID:
openfiles /Disconnect /s lon-fs01 /ID 617909089
We can forcefully reset all sessions and unlock all files opened by a specific user:
openfiles /disconnect /s lon-fs01/u corp\mjenny /id *
Usually, force closing a file opened by a client on an SMB server may result in the loss of unsaved data. Hence, we carefully use the openfiles /disconnect command or the Close-SMBOpenFile cmdlet0.
[Need help to Close an Open File on a SMB Share? We are available 24*7]
Get-SMBOpenFile: Find and Close Open File Handlers Using PowerShell
New cmdlets to manage shares and files on an SMB server appeared in PowerShell version for Windows Server 2012/Windows 8. These cmdlets are to remotely close network connections to an open file.
We can get a list of open files using the
Get-SMBOpenFile cmdlet
.
Close-SmbOpenFile
is to close/reset the connection to a remote file.
To display a list of open files on the Windows SMB server, we run the command:
Get-SmbOpenFile | Format-List
The command returns the file ID, session ID and full file name (path).
We can display a list of open files with user and computer names (IP addresses):
Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessioID
We can list all files opened by a specific user:
Get-SMBOpenFile –ClientUserName “corp\bob”|select ClientComputerName,Path
or from a specific computer/server:
Get-SMBOpenFile –ClientComputerName 192.168.1.190| select ClientUserName,Path
,/pre>
We can display a list of open files by pattern. For example, to list all exe files opened from the shared folder:
Get-SmbOpenFile | Where-Object {$_.Path -Like “*.exe*”}
or open files with a specific name:
Get-SmbOpenFile | Where-Object {$_.Path -Like “*reports*”}
The Close-SmbOpenFile cmdlet is used to close the open file handler. You can close the file by ID:
Close-SmbOpenFile -FileId 4123426323239
But it is usually more convenient to close the file by name:
Get-SmbOpenFile | where {$_.Path –like “*annual2020.xlsx”} | Close-SmbOpenFile -Force
With the Out-GridView cmdlet, we can make a simple GUI form for finding and closing open files.
The following script will list open files. We should use the built-in filters in the Out-GridView table to find open files for which we want to reset the SMB sessions.
Then, we need to select the required files and click OK. As a result, the selected files will be forcibly closed.
Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID| Out-GridView -PassThru –title “Select Open Files”|Close-SmbOpenFile -Confirm:$false -Verbose
How to Close Open Files on Remote Computer Using PowerShell?
Now, let us see how our Support Engineers close Open Files on Remote Computer using PowerShell.
The Get-SMBOpenFile and Close-SmbOpenFile cmdlets can be used to remotely find and close open (locked) files.
First, we need to connect to a remote Windows SMB server via a CIM session:
$sessn = New-CIMSession –Computername lon-fs01
We can also connect to a remote server to run PorwerShell commands using the PSRemoting cmdlets:
Enter-PSSession or Invoke-Command.
The following command will find the SMB session for the open file
pubs.docx
and close the file session:
Get-SMBOpenFile -CIMSession $sessn | where {$_.Path –like “*pubs.docx”} | Close-SMBOpenFile -CIMSession $sessn
We confirm closing of the file by pressing Y. As a result, we have unlocked the file. Now, other users can open it.
To remove the confirmation of force closing a file on a SMB server, we use the -Force key.
With PowerShell, we can close SMB sessions and unlock all files that a specific user has opened.
For example, to reset all file sessions of the user bob, we run the command:
Get-SMBOpenFile -CIMSession $sessn | where {$_.ClientUserName –like “*bob*”}|Close-SMBOpenFile -CIMSession $sessn
[Get our 24/7 support. Our server specialists will keep your servers fast and secure.]
Conclusion
In short, this usually happens if the desktop software does not work as expected, the user logs off incorrectly, or when the user opened a file and forgot to close it. Today, we saw how our Supprt Engineers go about with this issue.
In enterprise environments, documents and other file types are often located on central file server and users open their documents directly from there. Sometimes, server administrators need to update such files, but can’t because at least one user is using it and locking the file.
You could of course just reboot the server and the file would be unlocked, but that might be overkill as you are throwing everybody out.
Luckily, there is a tool on the server, that lets you selectively unlock files, here is how to do it:
- On Windows 2008 R2 Server, click Start and type Share and Storage Management and press Enter
- In the right pane, click Manage Open Files
- Click Close Selected
- Click Yes to confirm
Be aware that users of that file might lose data.