0

i want to write a script that takes inputfrom the user and changes a word in a file to what the user entered. saw some people doing it like this:

(Get-Content c:\temp\test.txt).replace('word1', 'word2') | Set-Content c:\temp\test.txt

the problem is that i want to replace a word with a variable, so when i put it between the commas it wont work.

i want it to be something like that:

$word = read-host " please enter a word"
(Get-Content c:\temp\test.txt).replace('oldtext', '$word') | Set-Content c:\temp\test.txt

is there any way to do that?

UPDATE: tried it like this:

$path = "C:\Users\tc98868\Desktop\dsp.json"
$word = read-host "please enter a word"
(Get-Content $path).replace('dsp.tar.gz', $word) | Set-Content $path

and it still doesnt work.

Inian
  • 80,270
  • 14
  • 142
  • 161
ofribouba
  • 27
  • 3
  • 11

1 Answers1

2

Remove the single quote from the $word

PowerShell not expanding variables inside a single quote, it threat is as a string

$word = read-host " please enter a word"
(Get-Content c:\temp\test.txt).replace('oldtext', $word) | Set-Content c:\temp\test.txt

For PS Version 2:

(Get-Content c:\temp\test.txt) -replace 'oldtext', $word | Set-Content c:\temp\test.txt
Avshalom
  • 8,657
  • 1
  • 25
  • 43
  • tried it this way: $path = "C:\Users\tc98868\Desktop\dsp.json" $word = read-host "please enter a word" (Get-Content $path).replace('dsp.tar.gz', $word) | Set-Content $path and it still doesnt work.. have any idea why? – ofribouba Dec 06 '16 at 11:53