Replacing contents of a text file using PowerShell

If that is how you have the code exactly then I suppose it is because you have an opening single quote without a closing one. You are still going to have two other problems and you have one answer in your code. The >>> is the line continuation characters because the parser knows that the code is not complete and giving you the option to continue with the code. If you were purposely coding a single line on multiple lines you would consider this a feature.

$path = "c:\Users\$($env:username)\desktop\VPN.txt" 
(Get-Content $path) -replace "user1",$env:username | out-file $path 
  • Closed the path in quotes and used a variable since you called the path twice.
  • %name% is used in command prompt. Environment variables in PowerShell use the $env: provider which you did you once in your snippet.
  • -replace is a regex replaced tool that can work against Get-Content but you need to capture the result in a sub expression first.
  • Secondly with -replace is for regex and your string is not regex based you could just use .Replace() as well.
  • Set-Content is generally preferred over Out-File for performance reasons.

All that being said...

you could also try something like this.

$path = "c:\Users\$($env:username)\desktop\VPN.txt"
(Get-Content $path).Replace("user1",$env:username) | Set-Content $path 

Do you want to only replace the first occurrence?

You could use a little regex here with a tweak in how you get the use Get-Content

$path = "c:\Users\$($env:username)\desktop\VPN.txt" 
(Get-Content $path | Out-String) -replace "(.*?)user1(.*)",('$1{0}$2' -f $env:username) | out-file $path 

Regex will match the entire file. There are two groups which it captures.

  1. (.*?) - Up until the first "user1"
  2. (.*) - Everything after that

Then we use the format operator to sandwich the new username in between those capture groups.


Use:

(Get-Content $fileName) | % {
    if ($_.ReadCount -eq 1) {
        $_ -replace "$original", "$content"
    }
    else {
        $_
    }
} | Set-Content $fileName

Tags:

Powershell