최고의 답변자
Add text to file

질문
-
Hi
I am trying to get the content of a file or multiple files, if a pattern exists within the files, i want to start a new line after the pattern, and then add some content. Below is what i have started with, any help or advice would be great. I want to add the line at the bottom after the pattern, but i am stuck.
$IKey = xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxxx
$fileName = "C:\TempPath\ApplicationInsights.config"
$content = "<InstrumentationKey>$IKey</InstrumentationKey>"
$line = <ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
Get-Content $fileName |
Foreach-Object {
if ($_ -match $line)
{
Add-content $fileName "`n$content"
}
}
Thanks
Shane
- 편집됨 Shane W 2019년 4월 18일 목요일 오전 11:17
답변
-
I like this simple solution from https://stackoverflow.com/questions/1875617/insert-content-into-text-file-in-powershell
(Get-Content $fileName) | Foreach-Object { $_ if ($_ -match $line) {
$content
} } | Set-Content $fileName
모든 응답
-
In addition to what JRV said, you're missing the beginning and end "'" in the assignment to the $line variable. You also have regex metacharacters in you search pattern.
Try using the "$r" variable in the example below as the pattern in your "-match" to avoid unintentional matches (unlikely in this case, but it's still a "good thing"):
$line = '<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">' $r = [RegEx]::Escape($line)
--- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)
-
$file = "C:\TempPath\ApplicationInsights.config" [xml]$xml = Get-Content $file $ns = $xml.DocumentElement.NamespaceURI $node = $xml.CreateElement('InstrumentationKey', $ns) $key = $xml.CreateTextNode('xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxxx') $node.AppendChild($key) | Out-Null $xml.ApplicationInsights.PrependChild($node) | Out-Null $xml.Save($file)
- 답변으로 제안됨 jrvModerator 2019년 4월 19일 금요일 오전 8:23
-
-
I like this simple solution from https://stackoverflow.com/questions/1875617/insert-content-into-text-file-in-powershell
(Get-Content $fileName) | Foreach-Object { $_ if ($_ -match $line) {
$content
} } | Set-Content $fileName