繁体   English   中英

Powershell - 替换文件中的字符串

[英]Powershell - replace string in file

我正在尝试编辑名为 prefs.cfg 的配置文件的内容。 它有两行:

Server.Name "test"
VoIP.Enabled "1"

我正在尝试更轻松地替换字符串,但我似乎一直在搞砸。

我写了一些东西,如果有人能在我的脚本中指出我出错的地方,我将不胜感激。

$prefs = Get-Content .\prefs.cfg

$prefs | Select-String "Server.Name"

$servername = Read-Host -Prompt "Enter Server Name"

Write-Host $servername

$prefs -replace $servername

$prefs
  • 尽管您将$prefs传递给Select-String-replace ,但这些操作的结果并未分配给变量。 所以你以后不能使用它们。

  • 一个参数被传递给-replace 它期望两个:替换什么,替换什么。 编辑:如果提供了单个参数,则将其视为“要替换的内容”。 由于没有提供“用什么替换”,它将被替换为空(即删除)

  • Select-String-replace使用正则表达式。 这项任务似乎有点矫枉过正。 Where-Object.Replace完全可以.Replace这项任务。


$prefs = Get-Content .\prefs.cfg

# Get the line using Where. * is wildcard
$oldServerLine = $prefs | Where-object {$_ -like "Server.Name*"}

$servername = Read-Host -Prompt "Enter Server Name"

Write-Host $servername

# Replace old line with new line. ` is the escape character so you get " as expected.
$newPrefs = $prefs.Replace($oldServerLine,"Server.Name `"$servername`"")

$newPrefs

相关: -replace 和 .Replace 之间的区别

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM