如何将命令输出保存到变量,以及如何在Powershell中将该变量用作命令参数?

时间:2020-05-26 18:20:42

标签: powershell file variables

我想用当前用户的名称替换.cfg文件中的单词。

我知道$env:username输出当前用户。

这就是我得到的:

(Get-Content -path path\example.cfg -Raw) -replace 'TEST','current_user' | Set-Content path\example.cfg

我正在尝试用当前用户替换“ TEST”一词。

1 个答案:

答案 0 :(得分:2)

只需将您的文字字符串$替换为[,您就可以开始了:)

'current_user'

请注意,$env:username是正则表达式运算符,因此我们甚至可以限定所要查找的单词:

(Get-Content -path path\example.cfg -Raw) -replace 'TEST',$env:username | Set-Content path\example.cfg

-replace在正则表达式中表示“单词边界”,并可以帮助您避免部分替换“ {HOTTEST”或“ TESTICULAR”等单词中的(Get-Content -path path\example.cfg -Raw) -replace '\bTEST\b',$env:username | Set-Content path\example.cfg