Windows file server open files

Команда OPENFILES — управление открытыми по сети или локально файлами.

Команда OPENFILES используется для получения списка открытых файлов и папок в среде операционных систем Windows XP и старше. Возможно получение списка файлов, открытых удаленно с использованием сетевого доступа, или полного списка, включая файлы и папки, открытые локальными процессами. Кроме того, команда позволяет выполнить отключение сеансов удаленного открытия файлов или каталогов. Для работы с данной командой требуются права администратора ( «Запуск от имени администратора» в среде Windows 7 и старше)

Формат командной строки:

OPENFILES /параметр [аргументы]

/Disconnect — Отключение одного и более открытых файлов.

/Query — Отображение открытых файлов, локально и с сетевого ресурса.

/Local — Включает/отключает отображение локально открытых файлов.

Для получения справки по использованию команды с конкретным параметром используется следующий формат командной строки:

OPENFILES /Disconnect /? — отобразить подсказку по использованию команды OPENFILES с параметром /Disconnect

OPENFILES /Query /? | more — выдать подсказку по использованию параметра /Query в постраничном режиме вывода на экран

OPENFILES /Local /? > D:\oflocal.txt — выдать подсказку по использованию параметра /Local в текстовый файл D:\oflocal.txt

Примеры получения списка открытых файлов

Для управления режимом построения списка открытых файлов используется глобальный переключатель списка объектов (maintain objects list) текущее значение которого можно проверить командой :

Если флаг «построение списка объектов» включен, то команда OPENFILES отображает список файлов и папок, открытых как локально, так и по сети. Для отключения режима отображения списка файлов, открытых локальными процессами, используется команда:

openfiles /local off

Для вступления в силу нового режима построения списка открытых файлов, может потребоваться перезагрузка системы.

Список открытых файлов отображается с использованием команды OPENFILES /Query .

Формат командной строки:

OPENFILES /Query [/S система [/U пользователь [/P [пароль]]]] [/FO формат] [/NH] /V]

/S система — Подключаемый удаленный компьютер.

/U [ \]пользователь — Пользовательский контекст, в котором должна выполняться эта команда.

/P [пароль] — Пароль для этого пользовательского контекста.

/FO формат — Формат, в котором следует отобразить выходной файл. Допустимые форматы: «TABLE»,»LIST»,»CSV».

/NH — Указывает, что строка заголовков столбцов не должна отображаться. Допустимо только для форматов «TABLE», «CSV».

/V — Отображать расширенную информации в результатах.

/? — Вывод справки по использованию.

OPENFILES /Query /? — отобразить справку по использованию команды.

OPENFILES /Query — отобразить список открытых файлов и папок с параметрами по умолчанию.

OPENFILES /Query /FO CSV /NH — отобразить список открытых файлов в формате CSV — полей, разделяемых запятой, без отображения заголовков столбцов ( /NH ).

OPENFILES /Query /FO TABLE /V — отобразить список открытых файлов в виде таблицы (TABLE) с включением дополнительной информации (/V) об имени пользователя и идентификаторе процесса (PID). По умолчанию, используется список в формате таблицы, поэтому параметр /FO TABLE можно не указывать.

OPENFILES /Query /S /U /P — отобразить список открытых файлов на удаленном компьютере, с использованием имени пользователя и пароля, задаваемых в командной строке.

OPENFILES /S SERVER /U mydonain\user1 /P mypass — отобразить список открытых файлов на удаленном компьютере SERVER . Для выполнения команды на удаленном компьютере используется имя пользователя user1 в домене mydomain и пароль mypass . Если имя пользователя и пароль не заданы — используется учетная запись, в контексте которой выполняется команда OPENFILES

Читайте также:  Windows 10 исчезают окна

OPENFILES /S 192.168.0.1 /U mydonain\user1 /P mypass — то же, что и в предыдущем примере, но вместо имени удаленного компьютера, используется его IP-адрес.

OPENFILES /Query > C:\OpenedFiles.txt — записать результаты выполнения команды в текстовый файл C:\OpenedFiles.txt

Пример списка открытых файлов, полученного по команде OPENFILES /Query :

Список файлов, открытых локально:
———————-

ID
=====
8
48
8
8
668
. . .
Имя процесса
===============
dwm.exe
dwm.exe
taskhost.exe
explorer.exe
explorer.exe

Открыть файл (Путь\исполнимый файл)
==================================
C:\Windows\System32
C:\Windows\System32\ru-RU\dwm.exe.mui
C:\Windows\System32
C:\Windows\System32
C:\Windows\Fonts\StaticCache.dat

ID — уникальный идентификатор открытого файла или папки.

Имя процесса — имя процесса, открывшего файл или папку.

Открыть файл (Путь\исполнимый файл) — очевидно, не самый удачный перевод на русский язык. В данной колонке отображается имя и путь открытого файла или папки.

При использовании параметра /V в таблицу добавляются колонки:

Пользователь — имя пользователя, в контексте учетной записи которого открыт файл.

PID — уникальный идентификатор процесса, который открыл файл. В системе может быть несколько процессов имеющих оно и то же имя исполняемого файла (svchost.exe, cmd.exe и т.п.) однако каждый из них имеет уникальный PID, по значению которого можно выделить конкретный процесс. Пример отображаемой таблицы, полученной при выполнении команды с параметром /V :

ID
====
8
48
8
8
668
Пользователь
============
user1
user1
user1
user1
user1
PID
========
3284
3284
3292
3348
3348
Имя процесса
=============
dwm.exe
dwm.exe
taskhost.exe
explorer.exe
explorer.exe
Открыть файл (Путь\исполнимый файл)
==========================
C:\Windows\System32
C:\Windows\System32\ru-RU\dwm.exe.mui
C:\Windows\System32
C:\Windows\System32
C:\Windows\Fonts\StaticCache.dat

Пример таблицы открытых файлов, при выключенном переключателе построения списка локальных объектов ( параметр /Local OFF ) :

Информация: Флаг «построение списка объектов» должен быть включенным, чтобы видеть открытые локально файлы. Подробнее смотрите Openfiles /?.

ID
======
0
2
4
Пользователь
============
USER1
USER2
USER2
Тип
=======
Windows
Windows
Windows
Открытый файл (Путь\файл)
========================
C:\ERDC.7_64
C:\ERDC.7_64
C:\ERDC.7_64\bootmgr

В случае расширенного отображения данных ( параметр /V ), в таблицу добавляются колонки с именем узла, количеством блокировок при совместном использовании одного и того же файла разными пользователями ( #Locks ) и режим открытия (Чтение, Запись, Запись\Чтение):

Имя узла
========
TEST7
TEST7
ID
======
0
50
Пользователь
============
USER1
USER2
Тип
=======
Windows
Windows
#Locks
======
0
0
Режим открытия
==============
Чтение
Чтение
Открытый файл (Путь\файл)
========================
C:\ERDC.7_64
C:\EFI\microsoft\boot

Принудительное отключение сеансов удаленного открытия файлов

Для отключения файлов и папок, которые были удаленно открыты на общем ресурсе, используется параметр /Disconnect . Необходимо учитывать, что команда OPENFILES не предназначена для полного запрета сетевого доступа к файлам и папкам, а всего лишь выполняет сброс отдельной удаленной сессии.

Формат командной строки:

OPENFILES /Disconnect [/S система [/U пользователь [/P [пароль]]]] <[/ID идентификатор] /A пользователь] [/O режим]>[/OP открытый файл]

/S система — Подключаемый удаленный компьютер.

/U [домен\]пользователь — Пользовательский контекст, в котором должна выполняться эта команда.

/P [пароль] — Пароль для этого пользовательского контекста.

/ID идентификатор] — Отключение всех открытых файлов по идентификатору. Допускается использование подстановочного символа «*».

/A пользователь — Отключение всех открытых файлов указанным в параметре пользователем. Допускается использование «*».

/O режим — Отключение всех открытых файлов, с указанным в параметре режимом. Допустимые значения параметра: Read,Write или Read/Write. Допускается использование подстановочного знака»*».

/OP открытый файл — Отключение всех файлов, открытых указанным в параметре файлом. Допускается использование подстановочного символа «*».

/? — Вывод справки по использованию.

OPENFILES /Disconnect /ID 1 — сбросить подключение к файлу или папке с идентификатором 1

OPENFILES /Disconnect /A user1 — сбросить подключения, созданные пользователем user1 .

OPENFILES /Disconnect /O Read/Write — сбросить подключения, имеющие режим «Чтение\Запись»

OPENFILES /Disconnect /S SERVER /U user1 /P pass1 /ID * — выполнить сброс всех сессий ( /ID * ) на удаленном компьютере с именем SERVER . При подключении к удаленному компьютеру используется имя пользователя user1 и пароль pass1 .

How to View and Close Open Files in Windows Server SMB Share?

Windows file server administrators often have to force close the shared files that are open simultaneously by multiple users. This usually happens if the desktop software doesn’t work as expected, the user logs off incorrectly, or when the user opened a file and forgot to close it (went home, on vacation, etc.). In all these cases, the file on the shared network folder is still open (and locked) and cannot be modified by other users. Other users can see such a message when trying to open a locked file (depending on the application used): The document filename is locked for editing by another user. To open a read-only copy of his document, click…

In this article we’ll show you how to get the list of open files on a Windows file server, find out which user locked a file on a shared folder, and how to close (reset) file sessions to unlock open files.

View Open Files on a Shared Network Folder on Windows Server

You can get the list of files opened by users on Windows file server using the built-in Computer Management ( compmgmt.msc ) graphic snap-in.

Open the Computer Management console on your file server (or connect to the server remotely from the management console running on your computer) and go to System Tools -> Shared Folders -> Open files. A list of open files on current SMB server is displayed 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).

You can get the same list of open files using the built-in openfiles.exe console tool. For example, using the following command you can get the Session ID, username and full local path to the open file:

openfiles /Query /fo csv |more

You can display a list of open files on a remote server. For example, you need to list all open files in shared folders on the lon-fs01 host:

openfiles /Query /s lon-fs01 /fo csv

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, run this command:

openfiles /Query /s lon-fs01 /fo csv | find /i «filename.docx»

You can specify only a part of the file name. For example, you need to find out who opened an XLSX file containing “sale_report” in its name. Use the following pipe:

openfiles /Query /s lon-fs01 /fo csv | find /i «sale_report»| find /i «xlsx»

Of course you can find this file in the Computer Management GUI, but it’s less convenient (this console doesn’t provide search feature).

How to Forcibly Close an Open File on a SMB Share?

To close an open file, 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 your file server, it won’t 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 told, it returns the session ID of the open file. Using this session ID you can force close the file by resetting the SMB connection.

First, you 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

You can forcefully reset all sessions and unlock all files opened by a specific user:

openfiles /disconnect /s lon-fs01/u corp\mjenny /id *

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 can be used to remotely close network connections to an open file.

You can get a list of open files using the Get-SMBOpenFile cmdlet. Close-SmbOpenFile is used to close/reset the connection to a remote file.

To display a list of open files on the Windows SMB server, run the command:

The command returns the file ID, session ID and full file name(path).
You can display a list of open files with user and computer names (IP addresses):

You can list all files opened by a specific user:

Get-SMBOpenFile –ClientUserName «corp\mjenny»|select ClientComputerName,Path

or from a specific computer/server:

Get-SMBOpenFile –ClientComputerName 192.168.1.190| select ClientUserName,Path

You can display a list of open files by pattern. For example, to list all exe files opened from the shared folder:

or open files with a specific name:

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, you can make a simple GUI form for finding and closing open files. The following script will list open files. You should use the built-in filters in the Out-GridView table to find open files for which you want to reset the SMB sessions. Then you 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?

The Get-SMBOpenFile and Close-SmbOpenFile cmdlets can be used to remotely find and close open (locked) files. First, you need to connect to a remote Windows SMB server via a CIM session:

$sessn = New-CIMSession –Computername lon-fs01

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

Confirm closing of the file by pressing Y . As a result, you have unlocked the file. Now other users can open it.

With PowerShell, you can close SMB sessions and unlock all files that a specific user has opened (a user went home and didn’t release the open files). For example, to reset all file sessions of the user mjenny, run this command:

Get-SMBOpenFile -CIMSession $sessn | where <$_.ClientUserName –like "*mjenny*">|Close-SMBOpenFile -CIMSession $sessn

Читайте также:  Redirecting output file linux
Оцените статью