Windows 使用变量替换powershell中的单词
我想编写一个脚本,从用户那里获取输入,并将文件中的一个单词更改为用户输入的内容。 看到一些人这样做:Windows 使用变量替换powershell中的单词,windows,shell,powershell,replace,Windows,Shell,Powershell,Replace,我想编写一个脚本,从用户那里获取输入,并将文件中的一个单词更改为用户输入的内容。 看到一些人这样做: (Get-Content c:\temp\test.txt).replace('word1', 'word2') | Set-Content c:\temp\test.txt $path = "C:\Users\tc98868\Desktop\dsp.json" $word = read-host "please enter a word" (Get-Content $path).replac
(Get-Content c:\temp\test.txt).replace('word1', 'word2') | Set-Content c:\temp\test.txt
$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
问题是我想用一个变量来替换一个单词,所以当我把它放在逗号之间时,它就不起作用了
我希望它是这样的:
$word = read-host " please enter a word"
(Get-Content c:\temp\test.txt).replace('oldtext', '$word') | Set-Content c:\temp\test.txt
有办法吗
更新:
试着这样做:
(Get-Content c:\temp\test.txt).replace('word1', 'word2') | Set-Content c:\temp\test.txt
$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
它仍然不起作用。从
$word
PowerShell不在单个引号内展开变量,它是一个字符串
$word = read-host " please enter a word"
(Get-Content c:\temp\test.txt).replace('oldtext', $word) | Set-Content c:\temp\test.txt
对于PS版本2:
(Get-Content c:\temp\test.txt) -replace 'oldtext', $word | Set-Content c:\temp\test.txt
从
$word
PowerShell不在单个引号内展开变量,它是一个字符串
$word = read-host " please enter a word"
(Get-Content c:\temp\test.txt).replace('oldtext', $word) | Set-Content c:\temp\test.txt
对于PS版本2:
(Get-Content c:\temp\test.txt) -replace 'oldtext', $word | Set-Content c:\temp\test.txt
尝试这种方式:$path=“C:\Users\tc98868\Desktop\dsp.json”$word=read host“请输入一个单词”(获取内容$path)。替换($dsp.tar.gz',$word)|设置内容$path,但它仍然不起作用。。你知道为什么吗?试着这样做:$path=“C:\Users\tc98868\Desktop\dsp.json”$word=read host“请输入一个单词”(获取内容$path)。替换('dsp.tar.gz',$word)|设置内容$path,但仍然不起作用。。你知道为什么吗?相关:你在使用哪个版本的powershell?我在使用powershell 2.0相关:你在使用哪个版本的powershell?我在使用powershell 2.0