我正在尝试获取和修改.ini文件的内容,但是我需要确保我正在寻找的文本前面没有分号,这将指定该行已“注释掉” ”
.ini文件包含一个参数块,未注释的块被注释掉,如下所示。
; use the following 2 settings for Sierra external GPS
;GPSType=Sierra
;Interface=PPP
; use the following 3 settings for internal NMEA GPS
GPSType=NMEA
Interface=Serial
Com=4
我在我的管道中尝试了一个If语句,但是不允许这样做。
$EOF = {
Write-Host "Ending Program"
break
}
Write-Host "test Application Internal/External Modem Selector" -BackgroundColor Green -ForegroundColor Black
Write-Host
Write-Host "*** Please ensure test is not running ***" -ForegroundColor Yellow
Write-Host
if (!(Test-Path "C:\Program Files (x86)\Rogers\test\test.ini"))
{
Write-Host "Warning - test.INI not present" -BackgroundColor Black -ForegroundColor Red |
Return(0)
}
Write-Host
Write-Host "1. Convert for Internal modem (COM4)"
write-Host "4. Convert for External modem"
Write-Host "Q. Exit"
Write-Host
$menuresponse = Read-Host 'Choose the option >'
if ($menuresponse -eq "q") {
&$EOF
}
elseif ($menuresponse -eq "1")
{
(Get-Content "C:\Program Files (x86)\Rogers\test\test.ini") |
If (($_).notcontains(';Com'))
{
{
ForEach-Object {$_ -replace 'GPSType=Sierra' , ';GPSType=Sierra' } |
ForEach-Object {$_ -replace 'Interface=PPP' , ';Interface=PPP' } |
ForEach-Object {$_ -replace ';GPSType=NMEA' , 'GPSType=NMEA' } |
ForEach-Object {$_ -replace ';Interface=Serial' , 'Interface=Serial' } |
ForEach-Object {$_ -replace ';Com=.*' , 'Com=4' } |
Set-Content "C:\Program Files (x86)\Rogers\test\test.ini"
}
else
{
ForEach-Object {$_ -replace 'Com=.*' , 'Com=4'
Set-Content "C:\Program Files (x86)\Rogers\test\test.ini"
}
}
}}
elseif ($menuresponse -eq "4")
{
(Get-Content "C:\Program Files (x86)\Rogers\test\test.ini") |
If (($_).notcontains(';Com'))
{
{
ForEach-Object {$_ -replace ';GPSType=Sierra' , 'GPSType=Sierra' } |
ForEach-Object {$_ -replace ';Interface=PPP' , 'Interface=PPP' } |
ForEach-Object {$_ -replace 'GPSType=NMEA' , ';GPSType=NMEA' } |
ForEach-Object {$_ -replace 'Interface=Serial' , ';Interface=Serial' } |
ForEach-Object {$_ -replace 'Com=.*' , ';Com=6' } |
Set-Content "C:\Program Files (x86)\Rogers\test\test.ini"
}
else
{
Write-Host "Modem already set to External"
&$EOF
}
}
}
else
{ write-host "Invalid Choice"
}
Break
有没有办法确保我不会在.ini文件中对参数进行“双重评论”,方法是识别它是否在传递指令之前在它之前有分号?
答案 0 :(得分:2)
我需要确保我正在寻找的文字前面没有分号
由于您已经在使用正则表达式,为什么不在匹配中使用字符串锚点^的开头
ForEach-Object {$_ -replace '^GPSType=Sierra' , ';$0' } |
这将取代GPSType = Sierra,但仅限于该行的起点。如果该线条看起来像; GPSType = Sierra则不匹配
请注意在替换中使用$0
。它代表整个匹配字符串。使用它可以帮助防止双重打字。
你应该真正研究PowerShell's choice system。超级易于实现和更面向对象的方法。实现它的Here is an answer of mine
您可以链接-replace
,因此您不需要多个foreach-object
:'123' -replace '1','One' -replace '2','Two' -replace '3','Three'