none
Powershell - Search pattern within body tag then copy the whole tag RRS feed

  • Question

  • Hello,

    Please help.

    I tried to create a powershell script to search for special characters in each block then copy the whole block out.

    The file has multiple <OrderItem> </OrderItem> and I would like to copy the whole block that has special characters in it. 

    $script = Get-Content C:\Downloads\test.xml
    $contain = $script.Contains("<OrderItem%>")

    Foreach ($contain in $script)
        {if (Select-String -Pattern '“E', '(â', '“W', '(“.', 'º' ) {Out-File C:\Downloads\test2.xml} }

    Thanks so much,

    D.


    • Edited by N0oblet Tuesday, November 15, 2016 1:53 PM
    Tuesday, November 15, 2016 1:51 PM

Answers

  • But if you still want to go with the 'cheap' version you could try this:

    Get-Content C:\Downloads\test.xml | Foreach-Object {If ($_ -match '<OrderItem>.*</OrderItem>') { $_ | Out-File C:\Downloads\test2.xml -Append}}
    (untested)


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    • Marked as answer by N0oblet Tuesday, November 15, 2016 7:39 PM
    Tuesday, November 15, 2016 2:05 PM

All replies

  • If your 'source' file is really XML you can use some more sofisticated ways to work with. Here you can find a helpfull summary how to work with xml: Free Powershell Cookbooks .... and here the direct download link

    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    Tuesday, November 15, 2016 2:00 PM
  • But if you still want to go with the 'cheap' version you could try this:

    Get-Content C:\Downloads\test.xml | Foreach-Object {If ($_ -match '<OrderItem>.*</OrderItem>') { $_ | Out-File C:\Downloads\test2.xml -Append}}
    (untested)


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    • Marked as answer by N0oblet Tuesday, November 15, 2016 7:39 PM
    Tuesday, November 15, 2016 2:05 PM
  • Thanks so much!

    Tuesday, November 15, 2016 3:40 PM
  • If you think one of the replies you've got was helpful consider marking it as answer. That will help even others looking for the same or something similar

    Thanks


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    Tuesday, November 15, 2016 3:46 PM
  • Can you give me another code if I want to remove the whole tag (the one has special characters) out of the file after output to new file?

    Thanks

    Tuesday, November 15, 2016 7:39 PM
  • #eample
    [xml]$xml='<someroot><OrderItem>some stuff</OrderItem></someroot>'
    #to load file use this line
    #[xml]$xml=Get-Content $filepath
    $node = $xml.SelectSingleNode('//OrderItem')
    $node.ParentNode.RemoveChild($node)
    $xml.Save($filepath)
    
    


    \_(ツ)_/

    Tuesday, November 15, 2016 7:50 PM