powershell - 不区分大小写的 PowerShell 替换

标签 powershell replace case

我有以下 PowerShell 脚本:

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

只要检查的注册表项与我指定的情况 - “浏览器”完全匹配,脚本就可以正常工作。

但是,如果注册表项中的大小写不同,请说“BROWSER”或“Browser”,它不会进行替换。

我正在寻找某种方法来使 string.replace 不区分大小写。我知道我可以先使用 .tolower 或 .toupper 转换字符串以使比较更容易,但我不知道这个特定的注册表项或访问它的应用程序是否区分大小写,所以我不想改变大小写现有 key 。

是否有捷径可寻?

最佳答案

称我为迂腐,但虽然这里没有人是完全错误的,但也没有人为最终解决方案提供正确的代码。

您需要更改此行:

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

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

只要您的字符串中没有正则表达式字符(例如 *+[]() 等),奇怪的 [regex] 文本并不是绝对必要的。但是你用它更安全。此语法也适用于变量:
$NullSessionPipes =  $NullSessionPipes -ireplace [regex]::Escape($stringToReplace), $stringToReplaceItWith

关于powershell - 不区分大小写的 PowerShell 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9117623/

相关文章:

c++ - 坚持从文本文件中删除 "\r"! C++

sql - Oracle SQL 案例中的数字无效

mysql - 在 MySQL 的 WHERE 子句中使用 IF 来排序条件并更新列(节目表的列)

c# - LINQ to SQL lambda 表达式。 OrderBy、Case When、Dynamic Where

powershell - 使用PDFTK将PDF分成多页?

powershell - 如何阻止 PowerShell 解压 Enumerable 对象?

Java regex - 如果不是单词开头,则从字符串中删除短语

powershell - powershell将objectid转换为sid

powershell - "PowerShell on Target Machines"任务因 TFS 2017\Azure Dev Ops 中的错误而失败

javascript - 正则表达式替换字符串中的函数