Case-insensitive PowerShell replacement

Brad picture Brad · Feb 2, 2012 · Viewed 47.5k times · Source

I have the following PowerShell script:

$RegExplorer = Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\lanmanserver\parameters
$NullSessionPipes = "$($RegExplorer.NullSessionPipes)"
$NullSessionPipes
$NullSessionPipes =  $NullSessionPipes.replace("browser", "")
$NullSessionPipes

The script works fine as long as the registry key examining exactly matches the case I've specified - "browser".

However if the case was different in the registry key say "BROWSER" or "Browser" it doesn't do the replacement.

I'm looking for some way to make string.replace case insensitive. I know I could convert the string using .tolower or .toupper first to make comparison easier, but I don't know if this particular registry key or applications which access it are case sensitive, so I don't want to change the case of existing key.

Is there an easy way to do this?

Answer

Ryan Shillington picture Ryan Shillington · Mar 8, 2016

Call me pedantic but while nobody here was outright wrong, nobody provided the correct code for the final solution either.

You need to change this line:

$NullSessionPipes =  $NullSessionPipes.replace("browser", "")

to this:

$NullSessionPipes =  $NullSessionPipes -ireplace [regex]::Escape("browser"), ""

The strange [regex] text isn't strictly necessary as long as there are no regular expression characters (ex. *+[](), etc) in your string. But you're safer with it. This syntax works with variables too:

$NullSessionPipes =  $NullSessionPipes -ireplace [regex]::Escape($stringToReplace), $stringToReplaceItWith