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?
By default, the -replace operator is case-insensitive. To make it case sensitive, use -creplace . To make it explicitly case-insensitive, use -ireplace .
If you want to use the case sensitive version of like , use -clike . It is so case insensitive that the following returns true : "foo" -like "Foo" returns True but "foo" -eq "FoO" returns True - not what I expected.
If the string-to-be-replaced isn't found, the replace() method returns nothing. You don't need to assign a string to a variable to replace text in a string. Instead, you can invoke the replace() method directly on the string like: 'hello world'. replace('hello','hi') .
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
NullSessionPipes is a multi-string value and the replace method (in addition of being case-sensitive) may fail if there's more than one string in it. You can use the -replace operator. By default, all comparison operators are case-insensitive. Case-sensitive operators starts with 'c', like: -creplace,-ceq, etc.
Operators that starts with 'i' are case-insensitive, like -ireplace,-ieq, and they are the same as -replace, -ieq.
See the about_Comparison_Operators for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With