Если вы администрируете общие сетевые папки Windows, скорее всего вы периодически сталкиваетесь с просьбами пользователей принудительно закрыть файлы, открытые (заблокированные) в сетевых папках другими пользователями. Обычно это связано с некорректной работой программы, неправильном завершении сессии пользователя или ситуациях, когда пользователь открыл файл и забыл закрыть его (ушел домой, в отпуск и т.д.). Во всех этих случаях файл в сетевой папке оказывается заблокированным, и другие пользователи не могут вносить в него изменения.
В этой статье мы покажем, как получить список открытых файлов на файловом сервере Windows, узнать какие пользователи их используют, и способы сброса файловых сессий для разблокировки открытых файлов.
Содержание:
- Вывод списка открытых файлов в сетевой папке Windows
- Определяем пользователя, который открыл файл в сетевой папке с помощью Openfiles
- Как принудительно закрыть открытый файл в Windows?
- Get-SMBOpenFile: вывод списка открытых по сети файлов в PowerShell
- Как удаленно закрыть открытые SMB файлы с помощью PowerShell?
Вывод списка открытых файлов в сетевой папке Windows
Список открытых по сети файлов в Windows можно получить с помощью стандартной графической консоли Computer Management (Управление компьютером —
compmgmt.msc
).
Запустите на файловом сервере консоль Computer Management (или подключитесь к нему консолью удаленно со своего компьютера) и перейдите в раздел System Tools -> Shared Folders -> Open files (Служебные программы -> Общие папки -> Открыты файлы). В правой части окна отображается список файлов на сервере, открытых удаленно. В данном списке указан локальный путь к файлу, имя учетной записи пользователя, количество блокировок и режим, в котором открыт файл (Read или Write+Read).
Этот же список открытых файлов можно получит с помощью встроенной консольной утилиты Openfiles. Например, с помощью следующей команды можно получить id сессии, имя пользователя и полный локальный путь к открытому файлу:
Openfiles /Query /fo csv |more
При удаленном доступе пользователя к папке или файлу в сетевой папке (SMB) на сервере, для пользователя создается новая сессия. Вы можете управлять открытыми файлами с помощью идентификаторов этих сессий.
Вы можете вывести список открытых файлов на сервере удаленно. Например, чтобы вывести все открытые по сети файлы на сервере mskfs01, выполните:
Openfiles /Query /s mskfs01 /fo csv
Команда Openfiles позволяет также вывести список локально открытых файлов. Для этого на сервере нужно включить опцию Maintain Objects List (Построение списка объектов) командой
openfiles /local on
и перезагрузить сервер. После этого команда Openfiles будет отображать файлы, открытые локальными процессами (этот режим желательно использовать только для отладки, т.к. может негативно сказаться на производительности сервера).
Определяем пользователя, который открыл файл в сетевой папке с помощью Openfiles
Чтобы удаленно определить пользователя, который открыл (заблокировал) файл 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"
Можно, конечно найти открытый файл и в графической консоли Computer Management, но это менее удобно (в консоли нет возможности поиска).
Как принудительно закрыть открытый файл в Windows?
Чтобы закрыть открытый файл, нужно найти его в списке файлов секции Open Files и в контекстном меню выбрать пункт “Close Open File”.
Если на файловом сервере сотни открытых файлов, найти их в консоли будет непросто. Удобнее воспользоваться утилитой Openfiles. Как мы уже говорили, она возвращает ID сессии открытого файла. Вы можете принудительно закрыть файл и сбросить подключение пользователя по ID SMB сессии. Сначала нужно определить ID сессии открытого файла:
Openfiles /Query /s mskfs01 /fo csv | find /i "farm"| find /i ".xlsx"
Теперь можно принудительно отключить пользователя по полученному идентификатору SMB сессии:
Openfiles /Disconnect /s mskfs01 /ID 67109098
Можно принудительно сбросить все сессии и освободить все файлы, открытые определённым пользователем:
openfiles /disconnect /s mskfs01 /u corp\aivanova /id *
Обратите внимание, что принудительное закрытие файла, открытого клиентом на SMB сервере, вызывает потерю несохраненных данных. Поэтому команду
openfiles /disconnect
и командлет
Close-SMBOpenFile
(рассматривается ниже) нужно использовать с осторожностью.
Get-SMBOpenFile: вывод списка открытых по сети файлов в PowerShell
В версии PowerShell в Windows Server 2012/Windows 8 появились командлеты для управления сетевыми файлами и папками на SMB сервере. Эти командлеты можно использовать чтобы удаленно закрыть открытые по сети файлы.
Список открытых файлов можно получить с помощью командлета Get-SMBOpenFile. Чтобы закрыть файл (сбросить подключение), используется Close-SmbOpenFile.
Для вывода полного списка открытых файлов на сервере, выполните команду:
Get-SMBOpenFile
Команда возвращает ID файла, ID сессии и полное имя файла.
Можно вывести список открытых файлов с именами пользователей и компьютеров (IP адресами):
Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID
Можно вывести все файлы, открытые определенным пользователем:
Get-SMBOpenFile –ClientUserName "corp\aaivanov" |select ClientComputerName,Path
или с определенного компьютера (сервера):
Get-SMBOpenFile –ClientComputerName 192.168.12.170| select ClientUserName,Path
Можно вывести список открытых файлов по шаблону. Например, все открытые по сети exe файлы:
Get-SmbOpenFile | Where-Object {$_.Path -Like "*.exe*"}
или файлы с определенным именем:
Get-SmbOpenFile | Where-Object {$_.Path -Like "*защита*"}
Чтобы закрыть файл используется командлет
Close-SmbOpenFile
. Закрыть файл можно по ID:
Close-SmbOpenFile -FileId 4123426323239
Но обычно удобнее закрыть файл по имени:
Get-SmbOpenFile | where {$_.Path –like "*prog.xlsx"} | Close-SmbOpenFile -Force
С помощью
Out-GridView
можно сделать простую графическую форму для поиска и закрытия файлов. Следующий скрипт выведет список открытых файлов. Администратор должен с помощью фильтров в таблице Out-GridView найти, выделить нужные файлы и нажать ОК. В результате выбранные файлы будут принудительно закрыты.
Get-SmbOpenFile|select ClientUserName,ClientComputerName,Path,SessionID| Out-GridView -PassThru –title “Select Open Files”|Close-SmbOpenFile -Confirm:$false -Verbose
Как удаленно закрыть открытые SMB файлы с помощью PowerShell?
Командлеты Get-SMBOpenFile и Close-SmbOpenFile можно использовать чтобы удаленно найти и закрыть открытые файлы. Сначала нужно подключиться к удаленному SMB серверу Windows через CIM сессию:
$sessn = New-CIMSession –Computername mskfs01
Также вы можете подключаться к удаленному серверам для запуска команд через командлеты PSRemoting: Enter-PSSession или Invoke-Command .
Следующая команда найдет SMB сессию для открытого файла
*pubs.docx
и завершит ее.
Get-SMBOpenFile -CIMSession $sessn | where {$_.Path –like "*pubs.docx"} | Close-SMBOpenFile -CIMSession $sessn
Подтвердите закрытие файла, нажав
Y
. В результате вы разблокировали открытый файл. Теперь его могут открыть другие пользователи.
Чтобы убрать подтверждение закрытия файла на сервере, используйте ключ
–Force
.
С помощью PowerShell вы можете закрыть и разблокировать на файловом сервере все файлы, открытые определенным пользователем (пользователь ушел домой и не освободил файлы). Например, чтобы сбросить все файловые сессии для пользователя ipivanov, выполните:
Get-SMBOpenFile -CIMSession $sessn | where {$_.ClientUserName –like "*ipivanov*"}|Close-SMBOpenFile -CIMSession $sessn
На общедоступном сетевом ресурсе могут возникать ошибки доступа к файлам. Причиной этому является некорректно завершенная сессия пользователя, ошибки в работе ПО или просто кто-то открыл файл и не закрывает его. В такой ситуации файл оказывается заблокированным и не доступен для работы другим пользователям.
На общедоступном сетевом ресурсе могут возникать ошибки доступа к файлам. Причиной этому является некорректно завершенная сессия пользователя, ошибки в работе ПО или просто кто-то открыл файл и не закрывает его. В такой ситуации файл оказывается заблокированным и не доступен для работы другим пользователям.
Решить проблему доступа к файлу можно путем закрытия сеансов использующих этот файл. В этой статье я расскажу как определить кто открыл файл в сетевой папке и как закрыть это подключение.
Рассмотрим два способа:
- Через оснастку «Управление компьютером» консоли управления Windows;
- При помощи утилиты командной строки — Openfiles.
1 способ. Получаем список открытых файлов с помощью оснастки «Управление компьютером».
Для получения списка открытых файлов на файловом сервере воспользуемся оснасткой консоли «Управление компьютером». Для запуска оснастки нажимаем сочетание клавиш «Win + R» и набираем название оснастки «compmgmt.msc».
В иерархии оснастки переходим /Управление компьютером/Служебные программы/Общие папки/Открытые файлы.
В правой части оснастки появится список открытых файлов. Здесь можно увидеть имя пользователя открывшего файл, количество блокировок и режим доступа к файлу.
Закрываем файл. Чтобы закрыть сетевой файл открытый другим пользователем находим его в списке и в контекстном меню выбираем пункт «Закрыть открытый файл».
2 способ. Просмотр открытых файлов через командную строку утилитой Openfiles.
Утилита Openfiles дает нам более широкие возможности по поиску и закрытию заблокированных файлов.
C помощью openfiles можно просмотреть список открытых файлов на сервере удаленно. Для этого открываем командную и запускаем утилиту с параметрами.
Openfiles /Query /s FileServer
где
/Query — показывает все открытые файлы,
/s — определяет имя удаленного компьютера.
В случае, когда необходимо указать логин и пароль пользователя для подключения к удаленному компьютеру, задаются параметры: /u — логин пользователя, /p — пароль пользователя.
openfiles /query /s FileServer /u domain\admin /p p@ssw1234
По-умолчанию список файлов показан в формате таблицы, но есть параметры позволяющие изменить формат вывода:
Openfiles /Query /s FileServer /fo csv
/fo csv — выводит список в формате csv с разделителем запятая;
/fo list — показывает открытые файлы в формате списка;
/fo table — формат таблицы.
Если необходимо увидеть информацию о количестве блокировок файлов (#Locks) и в каком режиме открыт файл (чтение или запись), то можно воспользоваться параметром /v.
Openfiles /Query /s FileServer /v
Определяем кто открыл сетевой файл.
Чтобы найти пользователя, который открыл и заблокировал нужный нам файл запускаем Openfiles с командой find.
Openfiles /Query /s FileServer | find /i "anyfile.xlsx"
в команде find указан параметр /i, чтобы поиск был регистронезависимым.
После того когда мы узнали имя пользо
Закрываем заблокированный сетевой файл.
Закрыть открытый файл можно по id сессии таким способом:
openfiles /disconnect /id 26843578
Закрыть все сетевые подключения к файлам и папкам, которые открыл пользователь BadUser:
openfiles /disconnect /a BadUser
Закрыть все файлы и директории открытые в режиме чтение/запись:
openfiles /disconnect /o read/write
Закрыть все подключения к директории с именем «c:\myshare»:
openfiles /disconnect /a * /op "c:\myshare\"
Чтобы сбросить все сессии на удаленном сервере FileServer, которые открыл пользователь domain\baduser, независимо от id сессии:
openfiles /disconnect /s FileServer /u domain\baduser /id *
There are times when a file is open on a windows server and you need to view what user or process has it open. These open files can be locked and prevent users from editing, cause errors when upgrading software, hold up a reboot, and so on.
In this article, I will show you how to quickly view open files on Windows servers and workstations.
Both methods use built in Windows tools and work on most Windows versions (I’ve tested this on Server 2012, 2016, 2019, and Windows 10).
Video Tutorial
If you don’t like videos or want more details then continue reading.
This first method is used to view open files on a shared folder. This is the best way to troubleshoot locked files that users have left open. If you need to see what process has a file open then check out method 2.
Step 1: Right Click the start menu and select Computer Management
Another way to access computer management is to type in compmgmt.msc into the start menu search box.
You will need to open up this console on the computer or server that has the shared folder. For example, I have a server called file1 with a shared folder named HR. To see the open files on this share I will need to open up the computer management console from the file1 server.
Step 2: Click on Shared Folders, then click on open files
I can now see that the user rallen has the HR folder and the file adpro.txt open.
If I needed to I can right click the file and select “Close Open File”. This is something that needs to be done when a file is locked.
That’s it for method 1.
If you need to check who has permission to a file or folder then check out my guide How to view NTFS effective permissions.
Method 2: View open files using PowerShell
In this section, I’ll show you how to use the Get-SMBOpenFile cmdlet to view open files on Windows.
Example 1: Get all open files
get-smbopenfile
The above command will return the FileID, SessionID, and path.
Example 2: Display user and computer
Get-SmbOpenFile | select ClientUserName, ClientComputerName
The above command displays the user, computer, and file path for the open files.
Example 3: Get open files for a specific user
Get-SMBOpenFile –ClientUserName "adpro\robert.allen"|select ClientComputerName,Path,ClientUserName
The above command will get all open files for the user “robert.allen”
Example 4: Get open files on a specific computer
Get-SMBOpenFile -ClientComputerName 192.168.100.20 | select ClientComputerName, path
In the above example, I’m getting all open files on the computer with the IP address 192.168.100.20.
Methods 3: View open files using the resource monitor
If you need to see what process has an open file locked then use the resource monitor.
Step 1: Type Resource monitor into the start menu search box
This is the quickest way to access the Resource Monitor.
Another option is to open up the task manager, click the performance tab and then click Open Resource Monitor.
Step 2: Click on the disk tab in the resource monitor
Now that I have the resource monitor open I just need to click on the disk tab.
Now I can see all kinds of details about the disk activity such as files open, PID, read and write bytes per second, and more.
You can move the columns around so you can see the full file path.
I have a lot of disk activity you go stop the live monitoring so you can view the open file activity.
To stop the live monitoring go to monitor, then select stop monitoring.
If you liked this article, then please subscribe to our YouTube Channel for more Active Directory Tutorials.
- Home
- Windows
- Windows Server
- How-tos
-
Share
Opens a new window
-
Facebook
Opens a new window -
Twitter
Opens a new window -
Reddit
Opens a new window -
LinkedIn
Opens a new window
-
Sign Up
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.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;