What is the Set-Content method in PowerShell?
Overview
The Set-Content cmdlet is used to write new content to a file. It replaces the existing content in the file. This cmdlet creates the file if it doesn't exist.
Syntax
Set-Content -Path "path to file" -Value "content"
Parameters
The function takes the following mandatory parameters:
Path: We provide the path to the file.
Value: We provide content to this parameter.
Return value
It writes content provided by the Value parameter to the file provided by the Path parameter.
Example
#!/usr/bin/pwsh -Command#Writing content to a fileSet-Content -Path "./data.txt" -Value "This is a test file"#Reading content from a fileGet-Content -Path "./data.txt"
Explanation
- Line 4: We write the content given in the parameter
Valueto a file given in the parameterPathusing the cmdletSet-Content. - Line 7: We read the content from a file we just created using the cmdlet
Get-Content.