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 file
Set-Content -Path "./data.txt" -Value "This is a test file"
#Reading content from a file
Get-Content -Path "./data.txt"

Explanation

  • Line 4: We write the content given in the parameter Value to a file given in the parameter Path using the cmdlet Set-Content.
  • Line 7: We read the content from a file we just created using the cmdlet Get-Content.

Free Resources