简体   繁体   中英

Powershell - replace string in file

I'm trying to edit the contents of a config file called prefs.cfg. It has two lines:

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

I'm trying to get more comfortable with replacing string but I seem to keep messing up.

I wrote something out, I would appreciate if someone could point in my script where I'm going wrong .

$prefs = Get-Content .\prefs.cfg

$prefs | Select-String "Server.Name"

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

Write-Host $servername

$prefs -replace $servername

$prefs
  • Although you are passing $prefs to Select-String and -replace , the results of those operations are not being assigned to variables. So you cannot use them later.

  • One argument is being passed to -replace . It expects two: what to replace, and what to replace it with. Edit: if a single argument is provided, this is taken as "what to replace". As "what to replace it with" is not provided, it will be replaced with nothing (ie deleted)

  • Select-String and -replace use regex. Seems a bit overkill for this task. Where-Object and .Replace are perfectly up to the task.


$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

Related: difference between -replace and .Replace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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