Vladimir Markiev
Vladimir Markiev

Reputation: 285

Powershell script will not overwrite the file, but it will create a new file and overwrtite it

I am using this Powershell script to replace the content of a file:

$lines = Get-Content -Path D:\file.txt -Encoding UTF8 -Raw
$option = [System.Text.RegularExpressions.RegexOptions]::Singleline 

$pattern1 = [regex]::new("(\[\.dfn \.term])#(.*?)#", $option)
$lines = $pattern1.Replace($lines, '$1_$2_')

$pattern2 = [regex]::new("(\[what you want])#(.*?)#", $option)
$lines = $pattern2.Replace($lines, '$1*$2*')

It is supposed to find some content in the file and overwrite the file. But it will not overwrite.

However, if I use the script like this:

$lines = Get-Content -Path D:\file.txt -Encoding UTF8 -Raw
$option = [System.Text.RegularExpressions.RegexOptions]::Singleline 

$pattern1 = [regex]::new("(\[\.dfn \.term])#(.*?)#", $option)
$lines = $pattern1.Replace($lines, '$1_$2_')

$pattern2 = [regex]::new("(\[what you want])#(.*?)#", $option)
$lines = $pattern2.Replace($lines, '$1*$2*')

$lines | Set-Content -Path D:\result.txt -Encoding UTF8 

The script will create a new file and write the result into it. And it will even overwrite result.txt every time the script is run. But if I explicitly say that I want to write the result to file.txt, it will not do that.

How to make the script overwrite the existing file?

My main tests were in Powershell version 5.1.19041.610

No explicit errors in the PS window and no changes to the file. But the file is replaced if I add $lines | Set-Content -Path D:\result.txt -Encoding UTF8 -Force

I also tested it on Powershell version 7.1.3.0.

No explicit errors in the PS window and no changes to the file. But the file is replaced if I add $lines | Set-Content -Path D:\result.txt -Encoding UTF8 without Force.

powershells

Upvotes: 1

Views: 1828

Answers (1)

Frenchy
Frenchy

Reputation: 17027

normally, Get-content opens, reads and closes the file

you could try

$lines | Set-Content -Path D:\result.txt -Encoding UTF8 -Force

-Force Override restrictions that prevent the command from succeeding. Force will replace the contents of a file, even if the file is read-only, but will not override security permissions. Without this parameter, read-only files are not changed.

Upvotes: 1

Related Questions