0

I can't seem to find an exact answer for my particular use in one location, so I am asking. I am very new to PowerShell, so the commands are foreign to me.

Using PowerShell, how can I search a file for all occurrences of "any string" between two specific strings and then output each occurrence of "any string" to another text file? Mind you, "any string" varies while the specific strings are the same each time.

Note: My code below actually searches all .xml files in a particular folder, which is what I want it to do.

Here's what I have currently:

$path    = "E:\files"
$outfile = "E:\testoutput.txt"
$files   = Get-Childitem $path *.xml -Recurse | Where-Object { !($_.psiscontainer) }
$pattern = "<Tag>(.*?)</Tag>"

# Loop through all the $files
foreach ($file in $files) {
  $file.Name | Out-File $outfile -Append

  # Loop through each line that matches $pattern
  Get-Content $file.FullName | Where-Object {$_ -match $pattern} | ForEach-Object {
    $_ | Out-File $outfile -Append
  }
}

This mostly works, but it places the "Tag" and "/Tag" (inside the angle brackets) into the output file, which I don't want. I only want what is between those tags. This is a very slow script, taking several minutes to complete on 165+ files. I have experimented with other code using Select-String that was very much faster, but it still included extra information I didn't want. Thank you for all of your help!

  • If this is being used for XML files why not look inot xml parsing capabilities of Powershell? – uSlackr Sep 19 '18 at 19:15
0

You can leverage XML parsing natively in Powershell! This way, you can simply read the content of the XML element instead of trying to regex everything.

$path    = "E:\files"
$outfile = "E:\testoutput.txt"
$files   = Get-Childitem $path *.xml -Recurse | Where-Object { !($_.psiscontainer) }
$elem = "Tag" #<- The name of the XML element to find

# Loop through all the $files
foreach ($file in $files) {
  $file.Name | Out-File $outfile -Append
  $doc = [xml](Get-Content $file.FullName) # <- Read in content as XML

  # Loop through each element named by $elem
  $doc.GetElementsByTagName($elem) |  ForEach-Object {
    $_ | Out-File $outfile -Append
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.