Home > Enterprise >  extracting zip file with powershell , reading the file and then extracting value between tags
extracting zip file with powershell , reading the file and then extracting value between tags

Time:10-21

I am pretty new to scripting and I have been stuck on this problem.

I want to extract a zip file and in that zip file there is a xml file called file.xml which I need to extract information from.

The file is huge and I only need to extract info between two tags.

<Report name="result\_many fail" summary="20" yes=19 no="1" finished=20> 

I need to extract information between the tags name and finished and save it to a txt file. The txt file should look like this:

name result_many fail, summary 20, yes 19 , no  1, finished 20

The problem is that it unzips to the right destination folder but it doesn't save anything into the result.txt file. My txt file is always empty.

This is my code:

echo "unzipping file..."
powershell "Expand-Archive C:\path_to_zip_file -Destinationpath C:\path_to_to_destination_folder;
$Path = “C:\path_to_to_destination_folder\file.xml;”
Select-Xml -XPath '//Report[@finished]').Node.InnerText;
Set-Content -Path 'C:\path_to_to_destination_folder\result.txt'

@echo "done"

Could someone help me out?

CodePudding user response:

Leaving aside incidental aspects of your question (seemingly calling from cmd.exe with a broken attempt to pass a multi-line command string, invalid sample XML, lack of a file argument to Select-Xml, lack of input to the Set-Content cmdlet):

$path = 'C:\path_to_to_destination_folder\file.xml'
(Select-Xml '//Report[@finished]' $path).
  Node.Attributes.ForEach({ $_.Name   ' '   $_.Value }) -join ', ' |
    Set-Content C:\path_to_to_destination_folder\result.txt

To call your PowerShell code from cmd.exe (a batch file) requires you to either pass it on a single line or to carefully spread it across multiple lines with line-continuations, using ^, based on the techniques described in this answer:

@echo off

echo unzipping file...

powershell -c Expand-Archive C:\path_to_zip_file -DestinationPath C:\path_to_to_destination_folder; ^
  $path = 'C:\path_to_to_destination_folder\file.xml'; ^
  (Select-Xml '//Report[@finished]' $path). ^
    Node.Attributes.ForEach({ $_.Name   ' '   $_.Value }) -join ', ' ^| ^
      Set-Content C:\path_to_to_destination_folder\result.txt

echo done

If you need help with the fundamentals, here are some PowerShell learning resources:

  • Related