我有一个这样的配置文件:
servername = 127.0.0.1
serverport = 44101
servername = 127.0.0.1
serverport = 0
#serverport = 44102
到目前为止,我有一个替换端口号的函数:
# Replace Ports. Syntax: Oldport=Newport
$WorkerPorts = @{44101=44201; 44102=44202; 44103=44203; 44104=44204}
function replacePort( $file, $Portarray )
{
Write-Host "Replacing Ports in $file"
foreach ($p in $Portarray.GetEnumerator())
{
Write-Host " Replace Port $($p.Name) with $($p.Value) ... " -NoNewLine
(Get-Content $file) |
Foreach-Object {$_ -replace $($p.Name), $($p.Value)} |
Set-Content $file
Write-Host "Done"
}
}
$DividerConf = "$strPath\divider\conf\divider.conf"
replacePort $DividerConf $WorkerPorts
但是,这也替换了被注释掉的端口(以 # 开头的行)。该函数应该如何仅替换不以 # 开头的行?我在想类似的事情:
function replacePort( $file, $Portarray )
{
Write-Host "Replacing Ports in $file"
foreach ($p in $Portarray.GetEnumerator())
{
if ( $content -match "^[^#]*$($p.Name)*" )
{
Write-Host " Replace Port $($p.Name) with $($p.Value) ... " -NoNewLine
(Get-Content $file) |
Foreach-Object {$_ -replace $($p.Name), $($p.Value)} |
Set-Content $file
Write-Host "Done"
}
}
}
但我无法找出正确的正则表达式。
编辑 好的,这就是我想要做的:更改我的配置文件中的端口
servername = 127.0.0.1
serverport = 44101
servername = 127.0.0.1
serverport = 0
#serverport = 44102
至
servername = 127.0.0.1
serverport = 44201
servername = 127.0.0.1
serverport = 0
#serverport = 44102
使用上面的 powershell 功能:
# Replace Ports. Syntax: Oldport=Newport
$WorkerPorts = @{44101=44201; 44102=44202; 44103=44203; 44104=44204}
$DividerConf = "$strPath\divider\conf\divider.conf"
function replacePort( $file, $Portarray )
{
#Here I need your help :)
}
replacePort $DividerConf $WorkerPorts
@Trevor:到目前为止,我通常会展示我的解决方案。否则,我认为我似乎在要求你做我的工作;)