- Открываем файл и читаем его содержимое с Get-Content в Powershell
- Получение данных
- Полное и построчное чтение с поиском
- Разделение файла
- Подсчет количества строк
- Кодировки
- Чтения файла под другим пользователем
- Непрерывное чтение
- Ограничение вывода строк
- Поиск файлов по содержимому
- Изменение файла с последующей записью
- Подсчет четных чисел в файле
- Out-File
- Syntax
- Description
- Examples
- Example 1: Send output and create a file
- Example 2: Prevent an existing file from being overwritten
- Example 3: Send output to a file in ASCII format
- Example 4: Use a provider and send output to a file
- Parameters
- Inputs
- Outputs
- Notes
Открываем файл и читаем его содержимое с Get-Content в Powershell
Для открытия файлов и чтения его содержимого используется команда Powershell Get-Content. В этой статье рассмотрим работу команды с открытием файла, построчным чтением, поиском по содержимому строки на примерах.
Навигация по посту
Получение данных
Для открытия файла ‘C:\text.txt’ можно использовать следующую команду:
Если у вас множество файлов или вы не уверены в назывании, то вы можете использовать подстановку. Символы подстановок бывают следующих типов:
- ‘*’ — говорит об неизвестном количестве символов;
- [a,b] — говорит, что в этом месте может быть буква ‘a’ или ‘b’;
- ? — обозначает один неизвестный символ.
Каждый из символов выше можно применять вместе и неограниченное число раз, в любой части пути и имени.
В этом примере я открою сразу два файла: lmhosts и hosts:
Следующие примеры вернут аналогичный результат:
Для похожей фильтрации есть следующие параметры, которые так же позволяют использовать символы подстановок:
- Include — в этом параметре мы добавляем шаблон, по которому будем включать файл;
- Exclude — с помощью этого параметра исключает файлы;
- Filter — исключает результаты.
Для каждого из этих параметров есть обязательно условие — использовать знак ‘*’ в конце пути.
Так мы вернем все файлы с расширением ‘.txt’:
В отличие от Filter, в Include и Exclude мы можем использовать несколько значений. В этом примере мы откроем файлы формата ‘.txt’ и ‘.ini’:
Полное и построчное чтение с поиском
По умолчанию, если мы будем передавать результат команды через конвейер Powershell вывод будет построчный. Это может составить проблему, так как при дополнительных условиях у нас будет возвращаться одна строка, а не весь текст:
Что бы текст передавался полностью, а не построчно — используйте параметр Raw:
Если вам вдруг понадобится выводить по 2 или более строк за раз, можно указать их количество через ReadCount:
Разделение файла
Файл выводится построчно из-за делиметра (разделителя), который по умолчанию равен ‘\n’ (идентификатор новой строки). Мы можем разделить файл иначе, например, использовав точку с запятой:
То есть результат выше — это массив. В массивах Powershell мы можем получать содержимое по индексам. В следующем примере я просто уберу точку с запятой:
Подсчет количества строк
Построчный вывод с командой Powershell позволяет посчитать количество строк во всем файле. Для подсчета используется команда Measure-Object:
Если нужна только цифра, а не объект, можно сделать так:
Кодировки
В параметре -Encoding можно указать следующие кодировки:
Как искать файлы используя Powershell Get-ChildItem
Чтения файла под другим пользователем
В этом командлете не предусмотрена возможность открытия файла под другим пользователем. При любых попытках вы будете получать ошибки:
- Access to the path is denied
- The FileSystem provider supports credentials only on the New-PSDrive cmdlet. Perform the operation again without specifying credentials.
Для обхода этих ошибок, если у вас нет другого выхода, нужно использовать Invoke-Command (команда удаленного подключения). Для ее настройки могут потребоваться дополнительные настройки описанные в другой статье.
Сам процесс открытия файла под другим пользователем будет выглядеть так:
Непрерывное чтение
С помощью параметра Wait вы можете читать файл, который в этот момент обновляется системой или другим пользователем:
Ограничение вывода строк
Можно ограничить вывод содержимого файла указав количество нужных строк в начале или конце:
- Head — выведет указанное количество строк с начала;
- Tail — выведет указанное количество строк с конца.
Так будут выведены только первые 5 строк:
Создание и изменение в Powershell NTFS разрешений ACL
Поиск файлов по содержимому
Get-Content не позволяет искать и открывать фалы находящиеся внутри других каталогов. Такой поиск называется рекурсивным и он доступен в Get-ChildItem.
В следующем примере мы вернем файлы из всех каталогов и подкаталогов:
File — возвращает только файлы. Каталоги нам не нужны.
С Get-ChildItem вы так же можете использовать Include,Exclude и Filter, которые были рассмотрены раннее. Использовать эти ключи лучше всего в первой команде т.к. это будет работать быстрее.
Через конвейер мы сможем открыть каждый файл, а с Select-Sting проверить есть ли в нем нужный текст. Так мы найдем файл с Powershell, который содержит строку ‘127.0.0.1’ в папке Windows:
Если убрать параметр Raw, то у нас выведется только та строка, которую мы искали:
Изменение файла с последующей записью
Вы так же можете изменить содержимое файла и перезаписать этот файл. Представим, что вам нужно заменить адрес ‘127.0.0.1’ в строке — это можно сделать так:
Или с помощью регулярного выражения (не точный шаблон):
Для записи в файл у нас есть два варианта. Первый — это использовать перенаправление в виде знака ‘>’, который перезапишет все содержимое файла или создаст новый файл:
Второй вариант — использовать команду Set-Content:
Функции по работе со строками в Powershell
Подсчет четных чисел в файле
У меня есть файл ‘file.txt’ со следующим содержанием:
Шаблон регулярного выражения ‘\d*\.?\d*’ говорит, что мы ищем число, после которого может быть точка, после которого могут быть еще числа. Таким образом мы захватим целые и числа с плавающей точкой.
Для выделения таких чисел из строк нужно использовать Select-String:
Нам нужно отформатировать вывод убрав пустые строки и получить значения свойства Value:
Мы можем вернуть остаток от деления использовав %. Если число делится на 2 с остатком 0, то оно будет четным:
Out-File
Sends output to a file.
Syntax
Description
The Out-File cmdlet sends output to a file. It implicitly uses PowerShell’s formatting system to write to the file. The file receives the same display representation as the terminal. This means that the output may not be ideal for programmatic processing unless all input objects are strings. When you need to specify parameters for the output, use Out-File rather than the redirection operator ( > ). For more information about redirection, see about_Redirection.
Examples
Example 1: Send output and create a file
This example shows how to send a list of the local computer’s processes to a file. If the file does not exist, Out-File creates the file in the specified path.
The Get-Process cmdlet gets the list of processes running on the local computer. The Process objects are sent down the pipeline to the Out-File cmdlet. Out-File uses the FilePath parameter and creates a file in the current directory named Process.txt. The Get-Content command gets content from the file and displays it in the PowerShell console.
Example 2: Prevent an existing file from being overwritten
This example prevents an existing file from being overwritten. By default, Out-File overwrites existing files.
The Get-Process cmdlet gets the list of processes running on the local computer. The Process objects are sent down the pipeline to the Out-File cmdlet. Out-File uses the FilePath parameter and attempts to write to a file in the current directory named Process.txt. The NoClobber parameter prevents the file from being overwritten and displays a message that the file already exists.
Example 3: Send output to a file in ASCII format
This example shows how to encode output with a specific encoding type.
The Get-Process cmdlet gets the list of processes running on the local computer. The Process objects are stored in the variable, $Procs . Out-File uses the FilePath parameter and creates a file in the current directory named Process.txt. The InputObject parameter passes the process objects in $Procs to the file Process.txt. The Encoding parameter converts the output to ASCII format. The Width parameter limits each line in the file to 50 characters so some data might be truncated.
Example 4: Use a provider and send output to a file
This example shows how to use the Out-File cmdlet when you are not in a FileSystem provider drive. Use the Get-PSProvider cmdlet to view the providers on your local computer. For more information, see about_Providers.
The Set-Location command uses the Path parameter to set the current location to the registry provider Alias: . The Get-Location cmdlet displays the complete path for Alias: . Get-ChildItem sends objects down the pipeline to the Out-File cmdlet. Out-File uses the FilePath parameter to specify the complete path and filename for the output, C:\TestDir\AliasNames.txt. The Get-Content cmdlet uses the Path parameter and displays the file’s content in the PowerShell console.
Parameters
Adds the output to the end of an existing file.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the type of encoding for the target file. The default value is utf8NoBOM .
The acceptable values for this parameter are as follows:
- ascii : Uses the encoding for the ASCII (7-bit) character set.
- bigendianunicode : Encodes in UTF-16 format using the big-endian byte order.
- bigendianutf32 : Encodes in UTF-32 format using the big-endian byte order.
- oem : Uses the default encoding for MS-DOS and console programs.
- unicode : Encodes in UTF-16 format using the little-endian byte order.
- utf7 : Encodes in UTF-7 format.
- utf8 : Encodes in UTF-8 format.
- utf8BOM : Encodes in UTF-8 format with Byte Order Mark (BOM)
- utf8NoBOM : Encodes in UTF-8 format without Byte Order Mark (BOM)
- utf32 : Encodes in UTF-32 format.
Beginning with PowerShell 6.2, the Encoding parameter also allows numeric IDs of registered code pages (like -Encoding 1251 ) or string names of registered code pages (like -Encoding «windows-1251» ). For more information, see the .NET documentation for Encoding.CodePage.
UTF-7* is no longer recommended to use. In PowerShell 7.1, a warning is written if you specify utf7 for the Encoding parameter.
Type: | Encoding |
Accepted values: | ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 |
Position: | 1 |
Default value: | UTF8NoBOM |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the path to the output file.
Type: | String |
Aliases: | Path |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Overrides the read-only attribute and overwrites an existing read-only file. The Force parameter does not override security restrictions.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the objects to be written to the file. Enter a variable that contains the objects or type a command or expression that gets the objects.
Type: | PSObject |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the path to the output file. The LiteralPath parameter is used exactly as it is typed. Wildcard characters are not accepted. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see about_Quoting_Rules.
Type: | String |
Aliases: | PSPath, LP |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
NoClobber prevents an existing file from being overwritten and displays a message that the file already exists. By default, if a file exists in the specified path, Out-File overwrites the file without warning.
Type: | SwitchParameter |
Aliases: | NoOverwrite |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies that the content written to the file does not end with a newline character. The string representations of the input objects are concatenated to form the output. No spaces or newlines are inserted between the output strings. No newline is added after the last output string.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the number of characters in each line of output. Any additional characters are truncated, not wrapped. If this parameter is not used, the width is determined by the characteristics of the host. The default for the PowerShell console is 80 characters.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
You can pipe any object to Out-File .
Outputs
None
Out-File does not generate any output.
Notes
Input objects are automatically formatted as they would be in the terminal, but you can use a Format-* cmdlet to explicitly control the formatting of the output to the file. For example, Get-Date | Format-List | Out-File out.txt
To send a PowerShell command’s output to the Out-File cmdlet, use the pipeline. Alternatively, you can store data in a variable and use the InputObject parameter to pass data to the Out-File cmdlet.
Out-File saves data to a file but it does not produce any output objects to the pipeline.