Replacing text file content with PowerShell

I looked around this whole site and it seems I can’t find anything suitable for my situation. In fact, I'm trying to write an add-on to the NETLOGON file, which will replace the text in a text file on all the desktops of our users. The current text is static in all directions.

The text I want to change will be unique to each user. I want to change the current text (user1) to the AD user name of the user (i.e. johnd, janed, etc.). I am using Windows Server 2008 R2 and all workstations are 64-bit version of Windows 7 Professional SP1.

Here is what I have tried so far (with several variables that none worked for one reason or another):

gc c:\Users\%USERNAME%\desktop\VPN.txt' -replace "user1",$env:username | out-file c:\Users\%USERNAME%\desktop\VPN.txt 

I did not get the error, but it also did not return to the usual prompt "PS C:>", just ">>>", and the file did not change as expected.

+6
source share
2 answers

If that is how you have the code, I assume it is because you have an open single quote without a closing quote. You have two more problems, and you have one answer in the code. >>> are line continuation characters, because the parser knows that the code is not complete and gives you the opportunity to continue working with the code. If you intentionally encoded one line on several lines, you would consider this function.

 $path = "c:\Users\$($env:username)\desktop\VPN.txt" (Get-Content $path) -replace "user1",$env:username | out-file $path 
  • Closed the path in quotation marks and used the variable since you called the path twice.
  • %name% used on the command line. PowerShell environment variables use the $env: provider, which you used once in your fragment.
  • -replace is a regular expression replacement tool that can work against Get-Content , but you need to write the result in a submenu first.
  • Secondly, with -replace for regex, and your line is not regex based, you can simply use .Replace() .
  • Set-Content usually preferable to Out-File for performance reasons.

All that is said ...

You can 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 only want to replace the first occurrence?

Here you can use a little regex with a tweak in how you 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 that he captures.

  • (.*?) - until the first "user1"
  • (.*) - Everything after that

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

+16
source

Using:

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

All Articles