- Работа с файлами и папками Working with Files and Folders
- Получение списка файлов и папок, содержащихся в папке Listing All the Files and Folders Within a Folder
- Копирование файлов и папок Copying Files and Folders
- Создание файлов и папок Creating Files and Folders
- Удаление всех файлов и папок, содержащихся в папке Removing All Files and Folders Within a Folder
- Подключение локальной папки как диска Mapping a Local Folder as a drive
- Чтение текстового файла в массив Reading a Text File into an Array
- How to print list of Files in a Folder in Windows 10
- Print list of files in a folder in Windows 10
- 1] Using Command Prompt
- 2] Using Paint
- 3] Use a freeware
- dir dir
- Синтаксис Syntax
- Параметры Parameters
- Комментарии Remarks
- Примеры Examples
Работа с файлами и папками Working with Files and Folders
Просмотр содержимого дисков Windows PowerShell и управление хранящимися на них элементами аналогично управлению файлами и папками на физических дисках Windows. Navigating through Windows PowerShell drives and manipulating the items on them is similar to manipulating files and folders on Windows physical disk drives. В этой статье описывается выполнение конкретных задач по управлению файлами и папками с помощью PowerShell. This article discusses how to deal with specific file and folder manipulation tasks using PowerShell.
Получение списка файлов и папок, содержащихся в папке Listing All the Files and Folders Within a Folder
Извлечь все элементы непосредственно из папки можно с помощью командлета Get-ChildItem . You can get all items directly within a folder by using Get-ChildItem . Для отображения скрытых и системных элементов добавьте необязательный параметр Force . Add the optional Force parameter to display hidden or system items. Например, эта команда отображает непосредственное содержимое диска C Windows PowerShell (которое совпадает с содержимым физического диска C Windows): For example, this command displays the direct contents of Windows PowerShell Drive C (which is the same as the Windows physical drive C):
Эта команда выводит только элементы, содержащиеся на диске непосредственно, так же как и команда DIR оболочки Cmd.exe или команда ls оболочки UNIX. The command lists only the directly contained items, much like using Cmd.exe ‘s DIR command or ls in a UNIX shell. Для показа вложенных элементов необходимо также указать параметр -Recurse . In order to show contained items, you need to specify the -Recurse parameter as well. (Время выполнения этой операции будет очень велико.) Для вывода всего содержимого диска C введите: (This can take an extremely long time to complete.) To list everything on the C drive:
Командлет Get-ChildItem позволяет отфильтровать элементы с помощью параметров Path , Filter , Include и Exclude , но обычно осуществляется лишь фильтрация по имени. Get-ChildItem can filter items with its Path , Filter , Include , and Exclude parameters, but those are typically based only on name. Сложную фильтрацию на основе других свойств элементов можно выполнить с помощью Where-Object . You can perform complex filtering based on other properties of items by using Where-Object .
Следующая команда находит все исполняемые файлы в папке Program Files, которые были в последний раз изменены после 1 октября 2005 г. и размер которых не менее одного мегабайта и не более десяти мегабайт: The following command finds all executables within the Program Files folder that were last modified after October 1, 2005 and which are neither smaller than 1 megabyte nor larger than 10 megabytes:
Копирование файлов и папок Copying Files and Folders
Копирование выполняется с помощью командлета Copy-Item . Copying is done with Copy-Item . Следующая команда создает резервную копию C:\boot.ini в C:\boot.bak: The following command backs up C:\boot.ini to C:\boot.bak:
Если целевой файл уже существует, то попытка копирования завершается неудачей. If the destination file already exists, the copy attempt fails. Чтобы перезаписать имеющийся целевой файл, используйте параметр Force . To overwrite a pre-existing destination, use the Force parameter:
Эта команда работает, даже если целевой объект доступен только для чтения. This command works even when the destination is read-only.
Так же выполняется и копирование папок. Folder copying works the same way. Эта команда копирует папку C:\temp\test1 в новую папку C:\temp\DeleteMe рекурсивно. This command copies the folder C:\temp\test1 to the new folder C:\temp\DeleteMe recursively:
Можно также скопировать избранные элементы. You can also copy a selection of items. Следующая команда копирует все файлы TXT, содержащиеся в папке C:\data , в папку C:\temp\text : The following command copies all .txt files contained anywhere in C:\data to C:\temp\text :
Для копирования элементов файловой системы можно использовать и другие средства. You can still use other tools to perform file system copies. В Windows PowerShell по-прежнему работают команды XCOPY, ROBOCOPY и такие COM-объекты, как Scripting.FileSystemObject . XCOPY, ROBOCOPY, and COM objects, such as the Scripting.FileSystemObject, all work in Windows PowerShell. Например, можно воспользоваться COM-классом Scripting.FileSystem сервера сценариев Windows для создания резервной копии файла C:\boot.ini в файле C:\boot.bak : For example, you can use the Windows Script Host Scripting.FileSystem COM class to back up C:\boot.ini to C:\boot.bak :
Создание файлов и папок Creating Files and Folders
Создание новых элементов осуществляется одинаковым образом всеми поставщиками Windows PowerShell. Creating new items works the same on all Windows PowerShell providers. Если поставщик Windows PowerShell поддерживает более одного типа элементов (например, поставщик Windows PowerShell FileSystem различает каталоги и файлы), необходимо указать тип элемента. If a Windows PowerShell provider has more than one type of item—for example, the FileSystem Windows PowerShell provider distinguishes between directories and files—you need to specify the item type.
Эта команда создает папку C:\temp\New Folder : This command creates a new folder C:\temp\New Folder :
Эта команда создает пустой файл C:\temp\New Folder\file.txt . This command creates a new empty file C:\temp\New Folder\file.txt
При использовании параметра Force с командой New-Item для создания папки, которая уже существует, она не перезапишет и не заменит папку. When using the Force switch with the New-Item command to create a folder, and the folder already exists, it won’t overwrite or replace the folder. Будет просто возвращен имеющийся объект папки. It will simply return the existing folder object. Однако, если использовать New-Item -Force в уже имеющимся файле, файл будет полностью перезаписан. However, if you use New-Item -Force on a file that already exists, the file will be completely overwritten.
Удаление всех файлов и папок, содержащихся в папке Removing All Files and Folders Within a Folder
Удалить вложенные элементы можно с помощью командлета Remove-Item , однако он потребует подтверждения удаления, если элемент сам что-нибудь содержит. You can remove contained items using Remove-Item , but you will be prompted to confirm the removal if the item contains anything else. Например, при попытке удаления папки C:\temp\DeleteMe , которая содержит другие элементы, Windows PowerShell предварительно предложит подтвердить удаление этой папки: For example, if you attempt to delete the folder C:\temp\DeleteMe that contains other items, Windows PowerShell prompts you for confirmation before deleting the folder:
Если подтверждение для каждого вложенного элемента нежелательно, задайте параметр Recurse : If you do not want to be prompted for each contained item, specify the Recurse parameter:
Подключение локальной папки как диска Mapping a Local Folder as a drive
Отобразить локальную папку можно с помощью команды New-PSDrive . You can also map a local folder, using the New-PSDrive command. Следующая команда создает локальный диск P: , корневым каталогом которого является локальный каталог Program Files, отображающийся только в сеансе PowerShell: The following command creates a local drive P: rooted in the local Program Files directory, visible only from the PowerShell session:
Как и при использовании сетевых дисков, диски, отображенные в Windows PowerShell, немедленно становятся доступными оболочке Windows PowerShell. Just as with network drives, drives mapped within Windows PowerShell are immediately visible to the Windows PowerShell shell. Чтобы создать подключенный диск, отображающийся в проводнике, нужен параметр -Persist . In order to create a mapped drive visible from File Explorer, the parameter -Persist is needed. Но с этим параметром можно использовать только удаленные пути. However, only remote paths can be used with Persist.
Чтение текстового файла в массив Reading a Text File into an Array
Одним из наиболее общих форматов хранения текстовых данных является файл, отдельные строки которого рассматриваются как отдельные элементы. One of the more common storage formats for text data is in a file with separate lines treated as distinct data elements. Командлет Get-Content используется для чтения всего файла за один шаг, как показано далее: The Get-Content cmdlet can be used to read an entire file in one step, as shown here:
Командлет Get-Content сразу рассматривает данные, считанные из файла, как массив с одним элементом на строку содержимого файла. Get-Content already treats the data read from the file as an array, with one element per line of file content. Убедиться в этом можно, проверив свойство Length полученного содержимого: You can confirm this by checking the Length of the returned content:
Эта команда наиболее полезна для непосредственного ввода в Windows PowerShell информационных списков. This command is most useful for getting lists of information into Windows PowerShell directly. Например, можно хранить в файле C:\temp\domainMembers.txt список имен компьютеров или IP-адресов по одному имени на каждую строку файла. For example, you might store a list of computer names or IP addresses in a file C:\temp\domainMembers.txt , with one name on each line of the file. Вы можете использовать командлет Get-Content , чтобы извлечь содержимое файла и поместить его в переменную $Computers : You can use Get-Content to retrieve the file contents and put them in the variable $Computers :
Теперь переменная $Computers представляет собой массив, содержащий в каждом элементе имя компьютера. $Computers is now an array containing a computer name in each element.
How to print list of Files in a Folder in Windows 10
If you ever need to print a list of files in a folder on your Windows 10/8/7 computer, here are a few ways you can do it. You can use the Command Prompt, Paint or a free software.
Print list of files in a folder in Windows 10
You can use any of the following methods to print a list of Files in a Folder in Windows 10.
- Run the Dir List command
- Use Paint software
- Use a freeware.
Let us see these methods in detail.
1] Using Command Prompt
Open the folder whose list of contents you want to print. Hold down Shift and right-click to open the hidden context menu items. You will see Open command window here. Click on it to open a command prompt window.
Else simply type CMD in the address bar and hit Enter to open the command prompt window there.
In the CMD type the following and press Enter:
A notepad text file will be immediately created in this folder. Open List.txt, and you will be able to see the list of the files in this folder.
Alternatively, you could also use the cd/ command to change the directory from the User directory to Downloads directory as follows:
2] Using Paint
Open the directory whos contents list you want to print. Select the Lists view. Press Alt+PrntScr. Next, open the built-in Paint application. Click Ctrl+V to copy-paste the contents of the clipboard here.
Now from the File menu of Paint select Print.
3] Use a freeware
You can print the name of every file on a drive, along with the file’s size, date and time of last modification, and attributes, Read-Only, Hidden, System, and Archive, with Karen’s Directory Printer. You can also sort the list of files by name, size, date created, date last modified, or date of last access. You can download it from its home page.
A) Simple File Lister does the function of DIR command for Windows OS to get a list of files in a directory and save them with their attributes to the user, in chosen .TSV, .CSV or .TXT formats, which you can then print. You can also select the File Attributes to be printed.
B) InDeep File List Maker lets you create and print a list of files in your folders, drives, and even in your DVDs/CDs.
D) Startup Discoverer is a portable freeware application, which lists start-up file & program locations and allows you to save and print them.
dir dir
Отображает список файлов и подкаталогов каталога. Displays a list of a directory’s files and subdirectories. Если используется без параметров, эта команда отображает метку тома диска и серийный номер, а затем список каталогов и файлов на диске (включая имена и дату и время последнего изменения). If used without parameters, this command displays the disk’s volume label and serial number, followed by a list of directories and files on the disk (including their names and the date and time each was last modified). Для файлов Эта команда отображает расширение имени и размер в байтах. For files, this command displays the name extension and the size in bytes. Эта команда также отображает общее число указанных файлов и каталогов, их совокупный размер и свободное место (в байтах), оставшееся на диске. This command also displays the total number of files and directories listed, their cumulative size, and the free space (in bytes) remaining on the disk.
Команда dir также может запускаться из консоли восстановления Windows с использованием различных параметров. The dir command can also run from the Windows Recovery Console, using different parameters. Дополнительные сведения см. в разделе Среда восстановления Windows (WinRE). For more information, see Windows Recovery Environment (WinRE).
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
[ :][ |
]
- d — каталоги d — Directories
- h — скрытые файлы h — Hidden files
- s — системные файлы s — System files
- l — точки повторного анализа l — Reparse points
- r — файлы только для чтения r — Read-only files
- a — файлы, готовые к архивации a — Files ready for archiving
- я — нет индексированных файлов содержимого i — Not content indexed files
Можно использовать любое сочетание этих значений, но не разделять значения с помощью пробелов. You can use any combination of these values, but don’t separate your values using spaces. При необходимости можно использовать двоеточие (:) или можно использовать дефис (-) в качестве префикса для обозначения, «not». Optionally you can use a colon (:) separator, or you can use a hyphen (-) as a prefix to mean, «not». Например, при использовании атрибута -s системные файлы не отображаются. For example, using the -s attribute won’t show the system files.
- n -в алфавитном порядке по имени n — Alphabetically by name
- e -в алфавитном порядке по расширению e — Alphabetically by extension
- сначала группировать каталоги g — Group directories first
- s -по размеру, самый маленький первый s — By size, smallest first
- d -по дате и времени, сначала старейшие d — By date/time, oldest first
- Используйте — префикс, чтобы изменить порядок сортировки на обратный Use the — prefix to reverse the sort order
Несколько значений обрабатываются в порядке их перечисления. Multiple values are processed in the order in which you list them. Не разделяйте несколько значений пробелами, но при необходимости можно использовать двоеточие (:). Don’t separate multiple values with spaces, but you can optionally use a colon (:).
Если параметр SortOrder не указан, dir/o Перечисляет каталоги в алфавитном порядке, за которым следуют файлы, которые также сортируются в алфавитном порядке. If sortorder isn’t specified, dir /o lists the directories alphabetically, followed by the files, which are also sorted alphabetically.
- c — создание c — Creation
- Последний доступ a — Last accessed
- w — Последнее написанное w — Last written
Комментарии Remarks
Чтобы использовать несколько параметров имени файла, разделяйте имена файлов пробелами, запятыми или точками с запятой. To use multiple filename parameters, separate each file name with a space, comma, or semicolon.
Можно использовать подстановочные знаки (* или ?) для представления одного или нескольких символов имени файла и отображения подмножества файлов или подкаталогов. You can use wildcard characters (* or ?), to represent one or more characters of a file name and to display a subset of files or subdirectories.
Можно использовать подстановочный знак *, чтобы заменить любую строку символов, например: You can use the wildcard character, *, to substitute for any string of characters, for example:
dir *.txt Список всех файлов в текущем каталоге с расширениями, которые начинаются с txt, например TXT, txt1, .txt_old. dir *.txt lists all files in the current directory with extensions that begin with .txt, such as .txt, .txt1, .txt_old.
dir read *.txt Список всех файлов в текущем каталоге, начинающихся с «Read» и с расширениями, которые начинаются с txt, например TXT, txt1 или .txt_old. dir read *.txt lists all files in the current directory that begin with read and with extensions that begin with .txt, such as .txt, .txt1, or .txt_old.
dir read *.* Перечисляет все файлы в текущем каталоге, которые начинаются с любого расширения. dir read *.* lists all files in the current directory that begin with read with any extension.
Подстановочный знак звездочки всегда использует короткое сопоставление имен файлов, поэтому могут возникнуть непредвиденные результаты. The asterisk wildcard always uses short file name mapping, so you might get unexpected results. Например, следующий каталог содержит два файла (t.txt2 и t97.txt): For example, the following directory contains two files (t.txt2 and t97.txt):
Можно ожидать, что при вводе dir t97\* будет возвращаться файл t97.txt. You might expect that typing dir t97\* would return the file t97.txt. Однако при вводе dir t97\* возвращается оба файла, так как подстановочный знак звездочки соответствует файлу t.txt2 для t97.txt с использованием его краткого сопоставления имен T97B4
1.TXT. However, typing dir t97\* returns both files, because the asterisk wildcard matches the file t.txt2 to t97.txt by using its short name map T97B4
1.TXT. Аналогичным образом при вводе del t97\* будут удалены оба файла. Similarly, typing del t97\* would delete both files.
Можно использовать вопросительный знак (?) в качестве замены для одного символа в имени. You can use the question mark (?) as a substitute for a single character in a name. Например, введите dir read. txt список всех файлов в текущем каталоге с расширением txt, которые начинаются с Read и следуют до трех символов. For example, typing dir read. txt lists any files in the current directory with the .txt extension that begin with read and are followed by up to three characters. Сюда входят Read.txt, Read1.txt, Read12.txt, Read123.txt и Readme1.txt, но не Readme12.txt. This includes Read.txt, Read1.txt, Read12.txt, Read123.txt, and Readme1.txt, but not Readme12.txt.
При использовании параметра/a с более чем одним значением в атрибутах эта команда отображает имена только тех файлов, которые имеют все указанные атрибуты. If you use /a with more than one value in attributes, this command displays the names of only those files with all the specified attributes. Например, при использовании /a с атрибутами r и -h (с помощью /a:r-h или /ar-h ) Эта команда отображает только имена нескрытых файлов только для чтения. For example, if you use /a with r and -h as attributes (by using either /a:r-h or /ar-h ), this command will only display the names of the read-only files that aren’t hidden.
Если указать более одного значения SortOrder , эта команда сортирует имена файлов по первому критерию, затем по второму критерию и т. д. If you specify more than one sortorder value, this command sorts the file names by the first criterion, then by the second criterion, and so on. Например, если вы используете /o с параметрами e и -s для SortOrder (с помощью /o:e-s или /oe-s ), эта команда сортирует имена каталогов и файлов по расширению с самым большим первым, а затем отображает окончательный результат. For example, if you use /o with the e and -s parameters for sortorder (by using either /o:e-s or /oe-s ), this command sorts the names of directories and files by extension, with the largest first, and then displays the final result. Сортировка по алфавиту по расширению приводит к тому, что имена файлов без расширений отображаются первыми, затем имена каталогов и имена файлов с расширениями. The alphabetic sorting by extension causes file names with no extensions to appear first, then directory names, and then file names with extensions.
При использовании символа перенаправления ( > ) для отправки выходных данных команды в файл или при использовании канала ( | ) для отправки выходных данных команды в другую команду необходимо использовать /a:-d и /b для вывода списка только имен файлов. If you use the redirection symbol ( > ) to send this command’s output to a file, or if you use a pipe ( | ) to send this command’s output to another command, you must use /a:-d and /b to only list the file names. Можно использовать filename с /b и /s , чтобы указать, что эта команда будет искать в текущем каталоге и его подкаталогах все имена файлов, соответствующие имени файла. You can use filename with /b and /s to specify that this command is to search the current directory and its subdirectories for all file names that match filename. Эта команда выводит только имя диска, имя каталога, имя файла и расширение имени файла (по одному пути на строку) для каждого найденного файла. This command lists only the drive letter, directory name, file name, and file name extension (one path per line), for each file name it finds. Прежде чем использовать канал для отправки выходных данных команды в другую команду, необходимо задать переменную среды TEMP в файле Autoexec. NT. Before you use a pipe to send this command’s output to another command, you should set the TEMP environment variable in your Autoexec.nt file.
Примеры Examples
Чтобы отобразить все каталоги друг за другом, в алфавитном порядке, в расширенном формате и приостанавливать после каждого экрана, убедитесь, что корневой каталог является текущим каталогом, и введите: To display all directories one after the other, in alphabetical order, in wide format, and pausing after each screen, make sure that the root directory is the current directory, and then type:
Выходные данные содержат корневой каталог, подкаталоги и файлы в корневом каталоге, включая расширения. The output lists the root directory, the subdirectories, and the files in the root directory, including extensions. Эта команда также выводит имена подкаталогов и имена файлов в каждом подкаталоге дерева. This command also lists the subdirectory names and the file names in each subdirectory in the tree.
Чтобы изменить предыдущий пример так, чтобы в dir отображались имена и расширения файлов, но имена каталогов не указаны, введите: To alter the preceding example so that dir displays the file names and extensions, but omits the directory names, type:
Чтобы напечатать список каталогов, введите: To print a directory listing, type:
При указании PRN список каталогов отправляется на принтер, подключенный к порту LPT1. When you specify prn, the directory list is sent to the printer that is attached to the LPT1 port. Если принтер подключен к другому порту, необходимо заменить PRN на имя нужного порта. If your printer is attached to a different port, you must replace prn with the name of the correct port.
Можно также перенаправить выходные данные команды dir в файл, заменив PRN именем файла. You can also redirect output of the dir command to a file by replacing prn with a file name. Можно также ввести путь. You can also type a path. Например, чтобы направить выходные данные команды dir в файл dir.doc в каталоге Records, введите: For example, to direct dir output to the file dir.doc in the Records directory, type:
Если dir.doc не существует, команда dir создаст ее, если каталог записей не существует. If dir.doc does not exist, dir creates it, unless the Records directory does not exist. В этом случае появится следующее сообщение: In that case, the following message appears:
Чтобы отобразить список всех имен файлов с расширением txt во всех каталогах на диске C, введите: To display a list of all the file names with the .txt extension in all directories on drive C, type:
Команда dir отображает в расширенном формате алфавитный список совпадающих имен файлов в каждом каталоге, который приостанавливается при каждом заполнении экрана до тех пор, пока не будет нажата любая клавиша для продолжения. The dir command displays, in wide format, an alphabetized list of the matching file names in each directory, and it pauses each time the screen fills until you press any key to continue.