How do I replace a line in a file using PowerShell?
Use the Replace method like this:
$file = 'D:\home\App_Config\Sitecore.config'
$find = ' <setting name="Media.MediaLinkServerUrl" value=" "/>'
$replace = ' <setting name="Media.MediaLinkServerUrl" value="https://newurl.com"/>'
(Get-Content $file).replace($find, $replace) | Set-Content $file
Try the following:
$file = 'D:\home\App_Config\Sitecore.config'
$regex = '(?<=<setting name="Media\.MediaLinkServerUrl" value=")[^"]*'
(Get-Content $file) -replace $regex, 'https://newurl.com' | Set-Content $file
* Re Set-Content
: In Windows PowerShell it uses your system's legacy single-byte character encoding by default (based on the active ANSI code page), so you may want to use -Encoding
to control the output file's encoding explicitly; PowerShell [Core] 6+ defaults to BOM-less UTF-8.
- Also note the required
(...)
around theGet-Content
call to ensure that the pipeline can write back to the same file thatGet-Content
has read from. - If there's a chance that the opening tag in question (
<setting ...>
) spans multiple lines, useGet-Content -Raw $file
(PSv3+) to read the entire file content as a single string (thanks, deadlydog);
without-Raw
,Get-Content
returns an array of strings, representing the input lines.
Due to using a regular expression to match your existing setting, any text currently inside value="..."
is matched, so this command will work even when run repeatedly.
By contrast, what you tried uses an effective literal (... value=" "
) to find what to replace, and after the 1st - successful - run, that literal no longer matches, and subsequent runs have no effect.
The command above uses a streamlined approach to replacement:
(?<=<setting name="Media.MediaLinkServerUrl" value=")
is a look-behind assertion ((?<=...)
) that matches, but doesn't capture what it matches: it finds the part up to and including the opening"
of the value you're trying to replaces, without making that prefix a part of what will get replaced.[^"]*
then matches the entire value, up to, but not including the closing"
. ([^"]
is a character set that matches any character other than (^
) a"
, and*
finds any (possibly empty) sequence of such characters.Therefore, because the regex captured only the value itself, all you need to specify as the replacement string is the new value.