1

I am using a modified version of the code in this post.

$fileToCheck = "c:\Users\me\desktop\test.txt"

$fileContents = Get-Content $fileToCheck

$line = $fileContents | Select-String "hosts" | Select-Object -ExpandProperty Line

if ($line -eq $null) {
    "String Not Found"
    exit
}

echo $line

$modifiedContents = $fileContents | ForEach-Object {$_ -replace $line,'hey'}

echo $modifiedContents

This is my test.txt file's contents:

X.Y:
  hosts: ["https://localhost:111"]

There are 2 whitespaces preceding hosts.

I am unable to get the line to be replaced. I've narrowed it down to the fact that it is probably due to one of the special characters that are being used in that line, which is causing the issue.

I've tried the modified code with the original data and everything works.

Not sure what gives in my case?

Thank you so much for your time.

Brian Lee
  • 85
  • 1
  • 1
  • 7
  • 1
    If your aim is to replace the whole line `' hosts: ["https://localhost:111"]'` with value `hey`, then you need to escape the special characters using `[regex]::Escape($line)`. Can you show us the desired output? – Theo Apr 30 '21 at 09:26
  • @Theo The desired output is actually ` hosts: ["https://a.b.c.d:111"]`. Thank you so much! – Brian Lee Apr 30 '21 at 09:47
  • In short: PowerShell's [`-replace`](https://stackoverflow.com/a/40683667/45375) _operator_ is _regex_-based and case-_insensitive_ by default. To perform _literal_ replacement, `\ `-escape metacharacters in the pattern or call `[regex]::Escape()`. By contrast, the `[string]` type's [`.Replace()`](https://learn.microsoft.com/en-US/dotnet/api/System.String.Replace) _method_ performs _literal_ replacement and is case-_sensitive_, _invariably_ in Windows PowerShell, _by default_ in PowerShell (Core). See the [answer to the linked duplicate](https://stackoverflow.com/a/64771432/45375). – mklement0 Apr 30 '21 at 12:28

1 Answers1

2

I took your script and changed -replace to .Replace() and it works fine:

$modifiedContents = $fileContents | ForEach-Object {$_.Replace($line,'hey')}

You're trying to do a literal replacement, but you're using -replace, which involves regexes and as Theo suggested in the comment you need to escape special characters if you want to stick to the -replace.

Michal Rosenbaum
  • 1,801
  • 1
  • 10
  • 18