Powershell добавить строку в файл

Обновлено: 06.07.2024

Writes new content or replaces existing content in a file.

Syntax

Description

Set-Content is a string-processing cmdlet that writes new content or replaces the content in a file. Set-Content replaces the existing content and differs from the Add-Content cmdlet that appends content to a file. To send content to Set-Content you can use the Value parameter on the command line or send content through the pipeline.

If you need to create files or directories for the following examples, see New-Item.

Examples

Example 1: Replace the contents of multiple files in a directory

This example replaces the content for multiple files in the current directory.

The Get-ChildItem cmdlet uses the Path parameter to list .txt files that begin with Test* in the current directory. The Set-Content cmdlet uses the Path parameter to specify the Test*.txt files. The Value parameter provides the text string Hello, World that replaces the existing content in each file. The Get-Content cmdlet uses the Path parameter to specify the Test*.txt files and displays each file's content in the PowerShell console.

Example 2: Create a new file and write content

This example creates a new file and writes the current date and time to the file.

Set-Content uses the Path and Value parameters to create a new file named DateTime.txt in the current directory. The Value parameter uses Get-Date to get the current date and time. Set-Content writes the DateTime object to the file as a string. The Get-Content cmdlet uses the Path parameter to display the content of DateTime.txt in the PowerShell console.

Example 3: Replace text in a file

This command replaces all instances of word within an existing file.

The Get-Content cmdlet uses the Path parameter to specify the Notice.txt file in the current directory. The Get-Content command is wrapped with parentheses so that the command finishes before being sent down the pipeline.

The contents of the Notice.txt file are sent down the pipeline to the ForEach-Object cmdlet. ForEach-Object uses the automatic variable $_ and replaces each occurrence of Warning with Caution. The objects are sent down the pipeline to the Set-Content cmdlet. Set-Content uses the Path parameter to specify the Notice.txt file and writes the updated content to the file.

The last Get-Content cmdlet displays the updated file content in the PowerShell console.

Example 4: Use Filters with Set-Content

You can specify a filter to the Set-Content cmdlet. When using filters to qualify the Path parameter, you need to include a trailing asterisk ( * ) to indicate the contents of the path.

The following command set the content all *.txt files in the C:\Temp directory to the Value empty.

Parameters

Specifies that the content should be read as a stream of bytes. This parameter was introduced in PowerShell 6.0.

A warning occurs when you use the AsByteStream parameter with the Encoding parameter. The AsByteStream parameter ignores any encoding and the output is returned as a stream of bytes.

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

This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.

Type:PSCredential
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

Specifies the type of encoding for the target file. The default value is utf8NoBOM .

Encoding is a dynamic parameter that the FileSystem provider adds to Set-Content . This parameter works only in file system drives.

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.

UTF-7* is no longer recommended to use. As of 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:Named
Default value:UTF8NoBOM
Accept pipeline input:False
Accept wildcard characters:False

Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt . Wildcard characters are permitted. The Exclude parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.

Type:String [ ]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:True

Specifies a filter to qualify the Path parameter. The FileSystem provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the FileSystem filter language in about_Wildcards. Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.

Type:String
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:True

Forces the cmdlet to set the contents of a file, even if the file is read-only. Implementation varies from provider to provider. For more information, see about_Providers. The Force parameter does not override security restrictions.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcard characters are permitted. The Include parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.

Type:String [ ]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:True

Specifies a path to one or more locations. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. 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.

Type:String [ ]
Aliases:PSPath, LP
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

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

Returns an object that represents the content. By default, this cmdlet does not generate any output.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the path of the item that receives the content. Wildcard characters are permitted.

Type:String [ ]
Position:0
Default value:None
Accept pipeline input:True
Accept wildcard characters:True

This Parameter is only available on Windows.

Specifies an alternative data stream for content. If the stream does not exist, this cmdlet creates it. Wildcard characters are not supported.

Stream is a dynamic parameter that the FileSystem provider adds to Set-Content . This parameter works only in file system drives.

You can use the Set-Content cmdlet to create or update the content of any alternate data stream, such as Zone.Identifier . However, we do not recommend this as a way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the Unblock-File cmdlet.

This parameter was introduced in PowerShell 3.0.

Type:String
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the new content for the item.

Type:Object [ ]
Position:1
Default value:None
Accept pipeline input:True
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

Inputs

You can pipe an object that contains the new value for the item to Set-Content .

Есть задача вставить текстовую строку в определенное место текстового файла. Сделать это можно множеством различных способов, в том числе и с помощью PowerShell. О том, как именно, и пойдет речь далее.

Итак, в папке C:\temp находится текстовый файл file.txt. Для начала выведем его содержимое командой:

вывод содержимого файла

В файле всего 5 строк и нам необходимо вставить дополнительную строку между третьей и четвертой. Действовать будем следующим образом:

Сначала возьмем исходный файл и поместим его содержимое в переменную. Команда Get-Content выгружает текстовый файл в виде массива, в котором элементами являются строки. Таким образом в переменной $FileOriginal мы получим массив строк:

$FileName = ″C:\temp\file.txt″
$FileOriginal = Get-Content $FileName

Затем создадим еще один массив строк, пустой:

Строку, которую необходимо вставить, помещаем в переменную:

[String]$string = ″String three and half.″

Теперь берем исходный массив $FileOriginal и в цикле построчно передаем его в новый массив $FileModified, попутно проверяя каждую строку. Если строка соответствует заданному условию, то после нее вставляется дополнительная строка:

Foreach ($Line in $FileOriginal) <
$FileModified += $Line
if ($Line -match ″three″)
>

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

Set-Content $fileName $FileModified -Force

Все это сохраняем в виде скрипта, запускаем его и получаем вот такой результат.

вставка одной строки

Если требуется вставить несколько строк, то можно немного изменить скрипт. С помощью конструкции Here-Strings добавим несколько строк в переменную $strings и уже эту переменную будем вставлять в текст:

$FileName = ″C:\temp\file.txt″
$FileOriginal = Get-Content $FileName
[String[]]$FileModified = @()

$strings = @″
String three and quarter.
String three and half.
″@

Foreach ($Line in $FileOriginal) <
$FileModified += $Line
if ($Line -match ″three″)
>
Set-Content $fileName $FileModified -Force

Получится примерно так.

вставка нескольких строк

И еще один возможный случай, когда надо не просто вставить новый текст, а заменить существующий. Для этого можно воспользоваться свойством Replace строки. Еще раз изменим скрипт:

Обычно в процессе работы PowerShell генерируются некоторые выходные данные. Для вывода этих данных существуют специальные Out-командлеты (командлеты, название которых начинается с Out-). Когда выполняемая команда PowerShell возвращает данные, они передаются по конвейеру на вход Out-командлета, который обрабатывает их и отправляет в устройство вывода (на экран, в файл, на принтер и т.п.).

Для просмотра этих командлетов выполним команду:

Get-Command -Verb Out

командлеты для вывода

Out-Host

Командлет Out-Host служит для вывода данных на экран. Например:

Get-Process powershell | Out-Host

Впрочем, добавлять Out-Host в конец команды совсем необязательно. В конце конвейера по умолчанию находится командлет Out-Default, который и перенаправляет все в Out-Host. Т.е. предыдущая команда эквивалентна команде:

Get-Process powershell | Out-Default

которая в свою очередь эквивалентна команде:

На самом деле механизм вывода еще запутаннее. Как вы помните, результатом работы PowerShell являются объекты. Out-командлеты не умеют работать с любыми объектами, а только со специальным типом объектов форматирования, поэтому при получении объекта вызывают один из командлетов форматирования (Format-*). Format-командлет предоставляет Out-командлету объекты форматирования, описывающие порядок построения выходных данных, а Out-командлет отправляет их в нужное устройство. Т.е. при выполнении команды:

в действительности отрабатывает команда:

Get-Process powershell | Format-Table | Out-Host

вывод по умолчанию

Хотя добавлять Out-Host в конец команды необязательно, но в некоторых случаях удобно. К примеру он имеет ключ Paging, с помощью которого можно организовать постраничный вывод:

Get-Process | Out-Host -Paging

постраничный вывод

Out-File

Командлет Out-File перенаправляет выходные данные в указанный файл, например:

Get-Process powershell | Out-File proc.txt

По умолчанию данные в файле перезаписываются. Запретить перезапись существующего файла можно, указав ключ NoClobber, а если необходимо дописывать данные в существующий файл, то можно использовать ключ Append, который добавляет данные в конец файла:

Get-Process powershell | Out-File proc.txt -Append

out-file

Для вывода в файл можно использовать сокращенный синтаксис. Например для записи:

Get-Process powershell >proc.txt

или для добавления в конец файла:

Get-Process powershell >>proc.txt

Out-GridView

Командлет Out-GridView выводит данные в виде графической таблицы, в которой их можно отфильтровать и отсортировать по нужному признаку. Для наглядности можно указать ключ Title, который будет отображаться в заголовке:

Get-Process | Out-GridView -Title processes

out-greedview

Начиная стретьей версии PowerShell Out-GridView поддерживает ключ PassThru, позволяющий передать полученные данные дальше по конвейеру. Например, можно вывести список процессов, в графической оснастке отобрать нужные и передать их командлету Stop-Process, который остановит выбранные процессы:

Get-Process | Out-GridView -PassThru | Stop-Process

out-gridview передача по конвейеру

Out-Null

Командлет Out-Null используется в том случае, если выходные данные отображать не нужно. Он отправляет полученные данные в устройство NULL, т.е. удаляет их. Для примера возьмем такую команду:

$process = Get-WmiObject win32_process -Filter ″Name = ′Notepad.exe′″
$process.Terminate()

Помимо основного действия (остановка процесса) она выводит много лишней информации. Чтобы избавится от нее, отправим вывод в Out-Null, например так:

out-null

Out-String

Командлет Out-String преобразует входные данные в массив строк. По сути Out-String преобразует объекты PowerShell в строки, с которыми дальше можно работать как с обычным текстом (форматировать, производить поиск и т.п.).

Для примера выведем процесс, сохраним его в переменную $a и посмотрим тип данных:

$a = Get-Process powershell
$a.GetType()

Затем скормим содержимое Out-String а вывод сохраним в переменную $b:

$b = $a | Out-String
$b.Get-Type()

Как видно из примера, на входе Out-String тип данных Process, а на выходе String.

преобразование объекта в строку

Out-String принципиально отличается от остальных out-командлетов. Поскольку обычные out-командлеты работают с конечным результатом предыдущих команд, то сами они не производят никаких выходных данных. Именно поэтому out-командлет обычно ставится последним в командной строке, ведь после него в конвейере не остается ничего, с чем могут работать другие командлеты.

В отличие от них Out-String принимает объекты, преобразует их в массив строк и передает дальше по конвейеру. По умолчанию данные накапливаются и возвращаются одной строкой, но с помощью ключа Stream можно указать вывод по отдельной строке для каждого объекта.

Для примера выведем список системных служб со всеми свойствами и отформатируем его в виде таблицы:

Get-Service | Format-Table -Property * -AutoSize

Поскольку ширина консоли граничена 80 символами, то большинство данных будет обрезано, что не очень здорово.

форматирование

Чтобы не обрезать вывод, направим его в Out-String и увеличим ширину:

Get-Service | Format-Table -Property * -AutoSize | Out-String -Width 1024

Теперь все данные попали на экран, но все равно выглядит не очень.

out-string

Исправим положение, передав вывод Out-String командлету Out-File:

Get-Service | Format-Table -Property * -AutoSize | Out-String -Width 1024 | Out-File service.txt

На выходе получаем файл с таблицей нужной ширины, а для просмотра есть полоса прокрутки. Таким образом можно создавать и просматривать таблицы практически любой ширины.

out-string + out-file

Out-Printer

Командлет Out-Printer перенаправляет вывод на принтер. Например:

Get-Service | Format-Table -Property * -AutoSize | Out-File service.txt -Width 1024
Get-Content service.txt | Out-Printer

out-printer

Вывод отправляется на принтер, заданный в системе по умолчанию. Для указания альтернативного принтера можно использовать ключ Name.

Результатом работы команды в PowerShell всегда является не текст, а объект. Это касается и работы с текстом. Каждая строка является отдельным объектом со своими свойствами и методами, которыми можно пользоваться для обработки текста.

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

$string = ″My name is Kirill″
$string | Get-Member

свойства и методы строки

Свойства

А свойство Chars позволяет обращаться к любому символу в строке по его номеру, например:

свойства строки

Кстати, к символам в строке можно обращаться без использования Chars, а как к элементам массива, по индексу:

А если указать отрицательное число, то массив будет перебираться с конца:

Также кроме одного символа можно указать диапазон, например:

обращение к элементам строки

Методы

Теперь возьмем строку и начнем над ней издеваться приступим к методам.

Метод Insert служит для вставки подстроки в исходную строку, начиная с указанного символа. Для примера вставим ″ .N″ в конец строки (после 17 символа):

Метод Remove удаляет символы из строки начиная с указанного символа, например:

Метод Replace находит в исходной строке подстроку и заменяет ее на другую, например:

методы insert, remove и replace

Метод Split разбивает строку на массив строк с помощью разделяющего символа или группы символов. Например так мы разобьем строку, используя в качестве разделителя пробел:

А так укажем в качестве разделителя букву е:

Если необходимо указать несколько разделителей, то достаточно просто перечислить их через запятую:

метод split

Метод Substring позволяет получить подстроку, сформированную из исходной строки. Есть два варианта использования этого метода. К примеру результатом выполнения следующей команды будет строка, полученная путем удаления из исходной строки заданного количества символов:

А таким способом мы получим подстроку, сформированную из исходной строки, начинающуюся с указанной позиции (8) и содержащую указанное количество символов (9):

метод substring

Метод Clone создает точную копию исходного объекта, например:

Метод CompareTo производит сравнение двух строк и выдает 0, если строки совпадают:

В случае несовпадения метод может выдать -1 (если первая строка больше второй) или 1 (если первая строка меньше второй). Также при использовании этого метода стоит учитывать, что регистр символов влияет на результат сравнения. Если необходимо сравнить строки без учета регистра, то можно воспользоваться статическим методом Compare, о котором чуть позже.

Метод Equals также сравнивает две строки и в зависимости от результата возвращает True или False:

Кстати, такой же результат получается при использовании оператора сравнения -eq:

$string -eq $string2

методы clone, compareto и equals

Метод Contains проверяет наличие в строке указанной подстроки, и в зависимости от результата возвращает True или False. Например:

Метод StartsWith проверяет, начинается ли строка с указанной подстроки:

а метод EndsWith проверяет, заканчивается ли исходная строка подстрокой:

Обратите внимание, что эти методы также чувствительны к регистру символов.

методы contains, startwith, endwith

Говоря о зависимости от регистра символов, стоит упомянуть еще два метода. Метод ToUpper переводит исходную строку в верхний регистр:

а метод ToLower соответственно в нижний:

методы toupper и tolower

С их помощью можно избавиться от регистрозависимости, например при поиске или сравнении:

избавление от регистрозависимости

Метод IndexOf находит индекс начала вхождения подстроки в исходной строке. Например, создадим строковую переменную:

$string = ″substring one, substring two, substring three″

Теперь выведем индекс начала вхождения подстроки (substring):

методы indexof и lastindexof

методы indexofany и lastindexofany

Методы PadLeft и PadRight позволяют дополнить исходный текст до нужного количества символов слева или справа. Для примера создадим новую переменную $string и посмотрим ее длину:

$string = ″my name is Vasya Pupkin″
$string.Length

Как видите, строка содержит 23 символа. Дополним ее точками до 26 символов слева:

а получившуюся строку дополним знаками вопроса до 30 символов справа:

В принципе, процесс можно не разбивать на части, а дополнить сразу с двух сторон:

методы padleft и padright

и лишние знаки вопроса в конце:

методы trimstart и trimend

Немного о типах данных. Текущий тип данных можно посмотреть с помощью метода GetType, например:

$a = ″string ″
$a.GetType()

В поле Name указан тип данных String (строка).

метод gettype

Строковые данные можно преобразовать в другой тип данных, для чего у строки имеется ряд методов. Для примера возьмем метод ToCharArray и с его помощью преобразуем строку в массив символов:

Если теперь проверить тип данных, то вместо String мы увидим тип Char[].

метод tochararray

Преобразовать тип данных можно и с помощью статического метода Convert. Для примера создадим переменную, содержащую строку, а затем преобразуем ее в число (Int32);

$string = ″123″
$int = [convert]::ToInt32($string)

статический метод convert

Статические методы

Кроме обычных к строке можно применять статические методы. Вывести их список можно все той же командой Get-Member с ключом -Static.

статические методы строки

Методов много, поэтому коротко пробежимся по некоторым из них.

Метод Concat используется для объединения нескольких строк. В качестве примера создадим три стоковых переменных и объединим их:

$a = ″one″
$b = ″two″
$c = ″three″
[string]::Concat($a,$b,$c)

Метод Join также объединяет несколько строк, но с использованием заданного разделителя. Например, объединим строки используя в качестве разделителя двоеточие:

статические методы concat и join

Метод Copy создает точную копию исходной строки:

Метод Compare производит сравнение двух строк и выдает 0 при их совпадении или 1\-1 при несовпадении, аналогично методу CompareTo:

Метод Equals также производит сравнение и выдает результат в виде True\False:

статические методы compare и equals

$a = ″string″
$b = ″String″

А теперь сравним их. Эта команда покажет, что строки идентичны:

использованием регистрозависимости и без

И еще пара интересных методов для проверки строк. Метод IsNullOrEmpty проверяет наличие строки, а также не является ли она пустой строкой:

Метод IsNullOrWhiteSpace тоже проверяет наличие строки, а также то, что строка содержит только white-space символы (пробел, табуляция, символ новой строки и т.п.):

Adds content to the specified items, such as adding words to a file.

Syntax

Description

The Add-Content cmdlet appends content to a specified item or file. You can specify the content by typing the content in the command or by specifying an object that contains the content.

If you need to create files or directories for the following examples, see New-Item.

Examples

Example 1: Add a string to all text files with an exception

This example appends a value to text files in the current directory but excludes files based on their file name.

The Path parameter specifies all .txt files in the current directory, but the Exclude parameter ignores file names that match the specified pattern. The Value parameter specifies the text string that is written to the files.

Use Get-Content to display the contents of these files.

Example 2: Add a date to the end of the specified files

This example appends the date to files in the current directory and displays the date in the PowerShell console.

The Add-Content cmdlet creates two new files in the current directory. The Value parameter contains the output of the Get-Date cmdlet. The PassThru parameter outputs the added contents to the pipeline. Because there is no other cmdlet to receive the output, it is displayed in the PowerShell console. The Get-Content cmdlet displays the updated file, DateTimeFile1.log .

Example 3: Add the contents of a specified file to another file

This example gets the content from a file and stores the content in a variable. The variable is used to append the content into another file.

  • The Get-Content cmdlet gets the contents of CopyFromFile.txt and stores the contents in the $From variable.
  • The Add-Content cmdlet updates the CopyToFile.txt file using the contents of the $From variable.
  • The Get-Content cmdlet displays CopyToFile.txt.

Example 4: Add the contents of a specified file to another file using the pipeline

This example gets the content from a file and pipes it to the Add-Content cmdlet.

The Get-Content cmdlet gets the contents of CopyFromFile.txt . The results are piped to the Add-Content cmdlet, which updates the CopyToFile.txt . The last Get-Content cmdlet displays CopyToFile.txt .

Example 5: Create a new file and copy content

This example creates a new file and copies an existing file's content into the new file.

  • The Add-Content cmdlet uses the Path and Value parameters to create a new file in the current directory.
  • The Get-Content cmdlet gets the contents of an existing file, CopyFromFile.txt and passes it to the Value parameter. The parentheses around the Get-Content cmdlet ensure that the command finishes before the Add-Content command begins.
  • The Get-Content cmdlet displays the contents of the new file, NewFile.txt .

Example 6: Add content to a read-only file

This command adds a value to the file even if the IsReadOnly file attribute is set to True. The steps to create a read-only file are included in the example.

  • The New-Item cmdlet uses the Path and ItemType parameters to create the file IsReadOnlyTextFile.txt in the current directory.
  • The Set-ItemProperty cmdlet uses the Name and Value parameters to change the file's IsReadOnly property to True.
  • The Get-ChildItem cmdlet shows the file is empty (0) and has the read-only attribute ( r ).
  • The Add-Content cmdlet uses the Path parameter to specify the file. The Value parameter includes the text string to append to the file. The Force parameter writes the text to the read-only file.
  • The Get-Content cmdlet uses the Path parameter to display the file's contents.

To remove the read-only attribute, use the Set-ItemProperty command with the Value parameter set to False .

Example 7: Use Filters with Add-Content

You can specify a filter to the Add-Content cmdlet. When using filters to qualify the Path parameter, you need to include a trailing asterisk ( * ) to indicate the contents of the path.

The following command adds the word "Done" the content of all *.txt files in the C:\Temp directory.

Parameters

Specifies that the content should be read as a stream of bytes. This parameter was introduced in PowerShell 6.0.

A warning occurs when you use the AsByteStream parameter with the Encoding parameter. The AsByteStream parameter ignores any encoding and the output is returned as a stream of bytes.

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

This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.

Type:PSCredential
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

Specifies the type of encoding for the target file. The default value is utf8NoBOM .

Encoding is a dynamic parameter that the FileSystem provider adds to the Add-Content cmdlet. This parameter works only in file system drives.

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.

UTF-7* is no longer recommended to use. As of 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:Named
Default value:UTF8NoBOM
Accept pipeline input:False
Accept wildcard characters:False

Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as *.txt . Wildcard characters are permitted. The Exclude parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.

Type:String [ ]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:True

Specifies a filter to qualify the Path parameter. The FileSystem provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the FileSystem filter language in about_Wildcards. Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.

Type:String
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:True

Overrides the read-only attribute, allowing you to add content to a read-only file. For example, Force overrides the read-only attribute but it does not change file permissions.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcard characters are permitted. The Include parameter is effective only when the command includes the contents of an item, such as C:\Windows\* , where the wildcard character specifies the contents of the C:\Windows directory.

Type:String [ ]
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:True

Specifies a path to one or more locations. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. 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.

Type:String [ ]
Aliases:PSPath, LP
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

Indicates that this cmdlet does not add a new line or carriage return to the content.

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

Returns an object representing the added content. By default, this cmdlet does not generate any output.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the path to the items that receive the additional content. Wildcard characters are permitted. The paths must be paths to items, not to containers. For example, you must specify a path to one or more files, not a path to a directory. If you specify multiple paths, use commas to separate the paths.

Type:String [ ]
Position:0
Default value:None
Accept pipeline input:True
Accept wildcard characters:True

This Parameter is only available on Windows.

Specifies an alternative data stream for content. If the stream does not exist, this cmdlet creates it. Wildcard characters are not supported.

Stream is a dynamic parameter that the FileSystem provider adds to Add-Content . This parameter works only in file system drives.

You can use the Add-Content cmdlet to change the content of any alternate data stream, such as Zone.Identifier . However, we do not recommend this as a way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the Unblock-File cmdlet.

This parameter was introduced in PowerShell 3.0.

Type:String
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the content to be added. Type a quoted string, such as This data is for internal use only, or specify an object that contains content, such as the DateTime object that Get-Date generates.

You cannot specify the contents of a file by typing its path, because the path is just a string. You can use a Get-Content command to get the content and pass it to the Value parameter.

Читайте также: