powershell 如何在两个单词之间进行检查,如果没有找到,如何在两个单词之间添加文本

igsr9ssn  于 5个月前  发布在  Shell
关注(0)|答案(1)|浏览(42)

我正在尝试更新我们的VPN配置文件AOVPN设备隧道和用户隧道.我想更新IpinterfaceMetric从0到9.
我在这里举一个例子
IF文件包含类似于以下内容的数据:

\[AOVPN Device Tunnel\]
IpDnsFlus=0
IpInterfaceMetric=0
NetworkOutageTime=0

\[AOVPN User Tunnel\]
IpDnsFlus=0
IpInterfaceMetric=0
NetworkOutageTime=0

字符串
因此,我试图做的是检查是否有IpinterfaceMetric在AOVPN设备隧道部分,如果没有添加IpInterfaceMetric在AOVPN设备隧道部分。同样的事情去AOVPN用户隧道。
我有脚本检查在整个rasphone文件,但我必须检查在节到节,并添加到每一节,如果它不能找到它在每一节。
有人能帮帮我吗?

[CmdletBinding()]

    Param (

    )

    $RasphonePath = Join-Path -Path $env:appdata -ChildPath '\Microsoft\Network\Connections\Pbk\rasphone.pbk'$RasphoneData = Get-Content $RasphonePath
    $RasphoneData = Get-Content $RasphonePath

    If($RasphoneData.Contains("IpInterfaceMetric=0")){

    Write-Verbose 'Updating IpInterfaceMetric setting in rasphone.pbk...'
    $RasphoneData | ForEach-Object { $_ -Replace 'IpInterfaceMetric=.*', 'IpInterfaceMetric=9' } | Set-Content -Path $RasphonePath -Force

    }

     else {
    Add-Content -Path $RasphonePath -Value "IpInterfaceMetric=9" | Set-Content -Path $RasphonePath -Force
    
    }

ldxq2e6h

ldxq2e6h1#

regex时间到了!

# replace values as needed, of course
$fileContent = Get-Content $Path
$matchStart= [regex]::escape('\[AOVPN Device Tunnel\]')
$matchEnd= [regex]::escape('\[AOVPN User Tunnel\]')
$lineSearched = [regex]::escape('IpInterfaceMetric')

# checks if there is anything between the given lines... or the lines in first place
# add ELSE and whetever control as needed
if ($fileContent -imatch "(?s)$matchStart(.|\s)*?$matchEnd") {

    #  check if the value you are looking is ABSENT
    if ($matches[0] -inotmatch $lineSearched) {

        # if it's absent, adds it righter after $matchStart
        $fileContent = $fileContent -replace "(?s)($startMatch)", "`$1$([Environment]::NewLine)$lineSearched"

        # writes the file
        $fileContent | Set-Content $Path
    }

}

字符串
当字符串使用正则表达式转义字符时,[regex]::escape()非常方便
同样,[Environment]::NewLine也非常适合自动添加环境友好的NewLines。

相关问题