Write or replace the content in an item.
Syntax
Set-Content [[[-path]| [-literalPath] ]string[]]
[-value] Object[]
[-include string[]] [-exclude string[]] [-filter string]
[-passThru] [-force] [-credential PSCredential]
[-whatIf] [-confirm] [CommonParameters]
key
-path string
The path to the item that will receive the content.
Wildcards are permitted.
-literalPath string
Like Path above, only the value is used exactly as typed.
No characters are interpreted as wildcards. If the path includes any
escape characters then enclose the path in single quotation marks.
-value Object
The new content for the item.
-include string
Change only the specified items in the Path.
Wildcards are permitted. e.g. "*.txt"
-exclude string
Omit the specified items.
Wildcards are permitted. e.g. "*.log"
-filter string
A filter in the provider's format or language.
The exact syntax of the filter (wildcard support etc) depends on the provider.
Filters are more efficient than -include/-exclude, because the provider
applies the filter when retrieving the objects, rather than having
PowerShell filter the objects after they are retrieved.
-passThru
Pass the object created by Clear-Variable through the pipeline.
(By default this switch is not set)
-force
Override restrictions that prevent the command from succeeding, apart
from security settings. e.g. Force will create file path directories
or override a files read-only attribute, but will not change file permissions.
-credential PSCredential
Present a user/password credential to validate access to the file.
This is not yet supported in any Windows PowerShell core commands.
-whatIf
Describe what would happen if you executed the command without actually
executing the command.
-confirm
Prompt for confirmation before executing the command.
CommonParameters:
-Verbose, -Debug,-ErrorAction,-ErrorVariable, -OutVariable.
Examples
Write a string into a text file:
PS C:\>Set-content -path C:\test.txt -value "Hello World"
Write the current date into a CSV file:
PS C:\>get-date | set-content C:\Test_date.csv
Edit-Replace some text in every line of the file foo.txt :
PS C:\>(get-content foo.txt) | foreach-object {$_ -replace "oldTxt", "newTxt"} | set-content foo.txt
The parentheses around (Get-Content) ensure that the Get operation is completed before the Set operation begins, wthout this the two functions would both try to access the file at the same time.
"A man should hear a little music, read a little poetry, and see a fine picture every day of his life, in order that worldly cares may not obliterate the sense of the beautiful which God has implanted in the human soul" - Goethe
Related:
Add-Content - Add to the content of the item
Get-Content - Get the content of the item at the specified location.
Clear-Content - Remove content from a file /item.
Get-Item
get-help - about_namespace