Posted in

Modify files using Powershell

You can modify the content of a file using the power shell.

# Define the file path

$filePath = "C:\path\to\your\file.txt"

# Define the new content you want to add to the file

$newContent = @"
This is the new content that will replace the old content in the file.
You can add multiple lines if necessary.
"@

# Write the new content to the file, overwriting any existing content

$newContent | Set-Content -Path $filePath

But there is also sometimes need to append the content instead of replace the content, for that you can follow the following code

# Define the file path

$filePath = "C:\path\to\your\file.txt"

# Define the new content you want to add to the file

$newContent = @"
This is the new content that will be added to the end of the file.
You can add multiple lines as needed.
"@

# Append the new content to the file

$newContent | Add-Content -Path $filePath

 

Complete Code:

# Define the file path

$filePath = "D:\Ansible\clk2f1\dns.dns"

# Define the new content you want to add to the file

$newContent = @"

192.168.1.1 sub.clk2f1.com

192.168.1.1 pub.clk2f1.com

"@

# Write the new content to the file, overwriting any existing content

$newContent | Set-Content -Path $filePath

# Define the file path

$filePath = "D:\Ansible\clk2f1\dns.dns"

# Define the new content you want to add to the file

$newContent = @"

192.168.2.1 cubes.clk2f1.com

192.168.2.1 pys.clk2f1.com

"@

# Append the new content to the file

$newContent | Add-Content -Path $filePath

Leave a Reply

Your email address will not be published. Required fields are marked *