如何取消注释配置文件中的一行并使用 PowerShell 编辑替换值

问题描述

我正在尝试使用 powershell 取消注释 conf 文件中名为 DebugLevel 的行或键,其当前注释如下。哈希(#)后面有一个空格,我想删除它,这样 D 将成为新行的第一个字符,就像服务器的放置方式一样。在名为 server 的文件中有另一个键,我需要更新它的值并将其指向其他名称,比如 demoenv。我目前正在使用带有替换参数的 Get-Content 并设置内容以输入新值,但是对于推荐的行,我如何取消注释并设置这样的值

# DebugLevel=3
DebugLevel=4 # i want to uncomment the above line,and set the value like this


解决方法

尝试使用下面的代替。

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-string?view=powershell-7.1

Select-String

# Get specifics for a module,cmdlet,or function
(Get-Command -Name Select-String).Parameters
(Get-Command -Name Select-String).Parameters.Keys
Get-help -Name Select-String -Examples
Get-Help -Name Select-String -Detailed
Get-help -Name Select-String -Full
Get-help -Name Select-String -Online

当然使用替换。您需要提供正确的 RegEx 来捕获您要替换的内容。

在此处查看类似的问答:

Powershell - Find and update all instances of named object property recursively