Search notes:

PowerShell cmdLet Set-Content

set-content creates or replaces a file and writes this file's text. In its most basic form, the cmdLet is given a file name and an array whose elements represent the lines in the file. The following example creates (or replaces) the file just-some.text:
set-content just-some.text 'first line', 'second line', 'third line'
Github repository about-PowerShell, path: /cmdlets/content/set/write-file.ps1
After running the statement, the content of just-some.text will be:
first line
second line
third line

Creating an empty file (mimicking the Unix touch command)

In order to mimic the Unix touch command to create an empty file (if it does not already exist), set-content can be used like so:
PS C:\users\rene\> set-content empty.file $null
PS C:\users\rene\> (get-itemProperty).length
0

DOS and Unix line endings

By default, set-content uses DOS line endings when writing a file (at least on Windows, that is).
In order to create a file that has Unix line endings, the array with the lines must first be joined with the Unix separator ("`n") and then written.
Because set-content by default also ends the file with a line separator, the -noNewLine must also be used. The final new line needs then to be added «manually», too.
$lines = 'foo', 'bar', 'baz'

set-content dos.txt     $lines
set-content unix.txt  (($lines -join "`n") + "`n" ) -noNewLine

format-hex dos.txt
format-hex unix.txt
Github repository about-PowerShell, path: /cmdlets/content/set/unix-vs-dos.ps1
Note, it seems that -noNewLine must appear as last element in this command as it causes an error if it directly follows set-content.

Alias sc vs sc.exe

A standard alias for set-content is sc.
So, if someone is used to invoke sc.exe (the Service Control Manager Configuration Tool) from cmd.exe by just typing the two letters sc, this might lead to unexpected results in a PowerShell console.
Therefore, to start the service configuration tool, it needs to be given its extension .exe:
PS C:\> sc.exe
…

See also

The command parameter -credential.
Powershell command noun: content
out-file
set-content belongs to the cmdlets with the -encoding parameter.
new-item -type file -value …
Set the Zone.Identifier stream to simulate a file being downloaded from the internet.

Index