Powershell

Set-Content: the PowerShell Way to Write to a File

PowerShell is an administrative scripting tool utilized for performing several tasks including modifying text files in the system. It offers a variety of cmdlets to write some content in the console or text file, “Set-Content” is one of them. More specifically, the “Set-Content” is used to write new content in a text file or replace the content in a text file. This command is specifically used to replace the content of several files with the new one.

This write-up will discuss various demonstrations of the “Set-Content” command.

How to Write/Output to a Text File in PowerShell Using the “Set-Content” Command?

As mentioned earlier, the “Set-Content” command is used to write into a new text file. However, it overwrites existing text in a file.

Example 1: Use the “Set-Content” Command to Write to a Single File
This example will demonstrate about writing content into a single file:

> Set-Content C:\Doc\New1.txt -value 'Hello World'

In this above-stated command:

  • First, add the “Set-Content” command and add the output file path.
  • After that, specify the “-Value” parameter and write the text within inverted commas:

Let’s execute the “Get-Content” command alongside the path of the output file path to get the exported content of a file inside the PowerShell console:

> Get-Content C:\Doc\New1.txt

Example 2: Use the “Set-Content” Command to Write to Multiple Files
You can also utilize the “Set-Content” command to write text to all the “.txt” files in the specific folder:

> Set-Content C:\Doc\*.txt -Value 'Hello world'

Here, we have added the wild character “*” along with the “.txt” extension at the folder path to select all the text files to write inside it:

For the verification, execute the following command:

> Get-Content C:\Doc\*.txt

That was all about writing to a file in PowerShell.

Conclusion

To write to a text file in PowerShell using the “Set-Content”, first, write the “Set-Content” command followed by the file path. After that, add the “-value” parameter and add the text within the inverted commas you want to write into a text file. This write-up has discussed in detail the use of the “Set-Content” command to write to a text file in PowerShell.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.