- Команда OPENFILES — управление открытыми по сети или локально файлами.
- Примеры получения списка открытых файлов
- Принудительное отключение сеансов удаленного открытия файлов
- Windows find user open file
- Syntax
- Parameters
- Remarks
- Examples
- openfiles
- openfiles /disconnect
- Syntax
- Parameters
- Examples
- openfiles /query
- Syntax
- Parameters
- Examples
- openfiles /local
- Syntax
- Parameters
- Examples
Команда 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
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 :
Пример таблицы открытых файлов, при выключенном переключателе построения списка локальных объектов ( параметр /Local OFF ) : Информация: Флаг «построение списка объектов» должен быть включенным, чтобы видеть открытые локально файлы. Подробнее смотрите Openfiles /?.
В случае расширенного отображения данных ( параметр /V ), в таблицу добавляются колонки с именем узла, количеством блокировок при совместном использовании одного и того же файла разными пользователями ( #Locks ) и режим открытия (Чтение, Запись, Запись\Чтение):
Принудительное отключение сеансов удаленного открытия файловДля отключения файлов и папок, которые были удаленно открыты на общем ресурсе, используется параметр /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 . Windows find user open fileSearches for a string of text in a file or files, and displays lines of text that contain the specified string. SyntaxParameters
] | Specifies the location and name of the file in which to search for the specified string. | ||||||||||||||||||||||||||||||
/? | Displays help at the command prompt. |
Remarks
If you don’t use /i, this command searches for exactly what you specify for string. For example, this command treats the characters a and A differently. If you use /i, however, the search becomes non-case-sensitive, and it treats a and A as the same character.
If the string you want to search for contains quotation marks, you must use double quotation marks for each quotation mark contained within the string (for example, «»This string contains quotation marks»»).
If you omit a file name, this command acts as a filter, taking input from the standard input source (usually the keyboard, a pipe (|), or a redirected file) and then displays any lines that contain string.
You can type parameters and command-line options for the find command in any order.
You can’t use wildcards (* and ?) in file names or extensions that you specify while using this command. To search for a string in a set of files that you specify with wildcards, you can use this command within a for command.
If you use /c and /v in the same command line, this command displays a count of the lines that don’t contain the specified string. If you specify /c and /n in the same command line, find ignores /n.
This command doesn’t recognize carriage returns. When you use this command to search for text in a file that includes carriage returns, you must limit the search string to text that can be found between carriage returns (that is, a string that is not likely to be interrupted by a carriage return). For example, this command doesn’t report a match for the string tax file if a carriage return occurs between the words tax and file.
Examples
To display all lines from pencil.ad that contain the string pencil sharpener, type:
To find the text, «The scientists labeled their paper for discussion only. It is not a final report.» in the report.doc file, type:
To search for a set of files, you can use the find command within the for command. To search the current directory for files that have the extension .bat and that contain the string PROMPT, type:
To search your hard disk to find and display the file names on drive C that contain the string CPU, use the pipe (|) to direct the output of the dir command to the find command as follows:
Because find searches are case-sensitive and dir produces uppercase output, you must either type the string CPU in uppercase letters or use the /i command-line option with find.
openfiles
Enables an administrator to query, display, or disconnect files and directories that have been opened on a system. This command also enables or disables the system Maintain Objects List global flag.
openfiles /disconnect
Enables an administrator to disconnect files and folders that have been opened remotely through a shared folder.
Syntax
Parameters
Parameter | Description |
---|---|
/s | Specifies the remote system to connect to (by name or IP address). Don’t use backslashes. If you don’t use the /s option, the command is run on the local computer by default. This parameter applies to all files and folders that are specified in the command. |
/u [ \] | Runs the command using the permissions of the specified user account. If you don’t use the /u option, system permissions are used by default. |
/p [ |
]
Note: You can use the openfiles /query command to find the file ID.
Examples
To disconnect all open files with the file ID 26843578, type:
To disconnect all open files and directories accessed by the user hiropln, type:
To disconnect all open files and directories with read/write mode, type:
To disconnect the directory with the open file name *C:\testshare*, regardless of who is accessing it, type:
To disconnect all open files on the remote computer srvmain that are being accessed by the user hiropln, regardless of their ID, type:
openfiles /query
Queries and displays all open files.
Syntax
Parameters
Parameter | Description |
---|---|
/s | Specifies the remote system to connect to (by name or IP address). Don’t use backslashes. If you don’t use the /s option, the command is run on the local computer by default. This parameter applies to all files and folders that are specified in the command. |
/u [ \] | Runs the command using the permissions of the specified user account. If you don’t use the /u option, system permissions are used by default. |
/p [ |
]
Displays the output in the specified format. Valid values include:
| |
/nh | Suppresses column headers in the output. Valid only when the /fo parameter is set to TABLE or CSV. |
/v | Specifies that detailed (verbose) information be displayed in the output. |
/? | Displays help at the command prompt. |
Examples
To query and display all open files, type:
To query and display all open files in table format without headers, type:
To query and display all open files in list format with detailed information, type:
To query and display all open files on the remote system srvmain by using the credentials for the user hiropln on the maindom domain, type:
In this example, the password is supplied on the command line. To prevent displaying the password, leave out the /p option. You’ll be prompted for the password, which won’t be echoed to the screen.
openfiles /local
Enables or disables the system Maintain Objects List global flag. If used without parameters, openfiles /local displays the current status of the Maintain Objects List global flag.
Changes made by using the on or off option don’t take effect until you restart the system. Enabling the Maintain Objects List global flag might slow down your system.
Syntax
Parameters
Parameter | Description |
---|---|
[on | off] | Enables or disables the system Maintain Objects List global flag, which tracks local file handles. |
/? | Displays help at the command prompt. |
Examples
To check the current status of the Maintain Objects List global flag, type:
By default, the Maintain Objects List global flag is disabled, and the following message appears, INFO: The system global flag ‘maintain objects list’ is currently disabled.
To enable the Maintain Objects List global flag, type:
The following message appears when the global flag is enabled, SUCCESS: The system global flag ‘maintain objects list’ is enabled. This will take effect after the system is restarted.
To disable the Maintain Objects List global flag, type: