Add text to file RRS feed

  • السؤال

  • 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="">
    Get-Content $fileName | 
        Foreach-Object {
            if ($_ -match $line) 
                Add-content $fileName "`n$content"



    • تم التحرير بواسطة Shane W 13/شعبان/1440 11:17 ص
    13/شعبان/1440 10:47 ص


جميع الردود

  • You cannot update a file that you are currently reading.  Send the output to a new file and then delete the old file and rename.


    13/شعبان/1440 12:08 م
  • 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="">'
    $r = [RegEx]::Escape($line)

    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)

    13/شعبان/1440 02:45 م
  • $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

    • تم الاقتراح كإجابة بواسطة jrvModerator 14/شعبان/1440 08:23 ص
    14/شعبان/1440 07:49 ص
  • Have you tried it?  Even if $line were properly quoted, it will add a blank line and $content to the bottom of the file for every match.  You could put parentheses around (Get-Content $fileName) so it finishes before add-content.

    • تم التحرير بواسطة JS2010 14/شعبان/1440 07:56 م
    14/شعبان/1440 07:24 م
  • I like this simple solution from

    (Get-Content $fileName) | 
        Foreach-Object {
            if ($_ -match $line) 
    } } | Set-Content $fileName
    • تم التحرير بواسطة JS2010 14/شعبان/1440 08:35 م
    • تم وضع علامة كإجابة بواسطة Shane W 18/شعبان/1440 09:10 ص
    14/شعبان/1440 07:51 م