很抱歉,很长的帖子。想详细解释。 我正在努力实现三件事,并且几乎要实现。可能是男生错误。尝试了嵌套循环等,但无法正常工作。
看来我需要分割$resultszone
数组。
\zones\
,test1.in-addr.arpa,test2.in-addr.arpa等之后的部分。示例源文件:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\Zones\test1.in-addr.arpa] "Type"=dword:00000001 "SecureSecondaries"=dword:00000002 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\Zones\test2.in-addr.arpa] "Type"=dword:00000001 "SecureSecondaries"=dword:00000002
预期结果
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\Zones\test1.in-addr.arpa] "Type"=dword:00000001 "DatabaseFile"="test1.in-addr.arpa.dns" "SecureSecondaries"=dword:00000002 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\Zones\test2.in-addr.arpa] "Type"=dword:00000001 "DatabaseFile"="test2.in-addr.arpa.dns" "SecureSecondaries"=dword:00000002
我设法使用下面的代码实现了所有目标,除了它为每一部分添加了一行,其中包括找到的区域的所有结果。
例如:
"DatabaseFile"="test1.in-addr.arpa test2.in-addr.arpa
#Get FileName Path
$FileName = "C:\temp\test.conf"
#Search for pattern in file and trim to desired format.
#Store array in $resultsZone
$resultszone = Select-String -Path "c:\temp\test.conf" -Pattern '(?<=Zones)(.*)' |
select -expa matches |
select -expa value |
% { $_.Trim("\]") }
# Get contents of file
(Get-Content $FileName) | ForEach-Object {
#Start Loop to find area of File to insert line
$_ # send the current line to output
if ($_ -match "type") {
#Add Line after the selected pattern (type) including area trimmed
"""DatabaseFile" + """=""" + $resultszone + ".dns" + """"
}
} | Set-Content C:\temp\elctest.conf
答案 0 :(得分:3)
我认为这可以满足您的需求:
$FileName = "C:\Temp\test.conf"
Get-Content $FileName | ForEach-Object {
$Match = ($_ | Select-String -pattern '(?<=Zones\\)(.*)').matches.value
if ($Match) { $LastMatch = ($Match).Trim("\]") }
$_
if ($LastMatch -and $_ -match 'type') {
"""DatabaseFile" + """=""" + $LastMatch + ".dns" + """"
}
} | Set-Content C:\Temp\elctest.conf
解决方法是,我们在循环中针对每一行执行Select-String
,然后将其匹配时存储在另一个变量(名为$LastMatch
)中,以便当我们到达想要的行时插入之前匹配的时间,我们就可以了。