【问题标题】:extracting zip file with powershell , reading the file and then extracting value between tags使用 powershell 提取 zip 文件,读取文件,然后在标签之间提取值
【发布时间】:2021-10-21 03:44:44
【问题描述】:

我对脚本很陌生,一直被这个问题困扰。

我想提取一个 zip 文件,在该 zip 文件中有一个名为 file.xml 的 xml 文件,我需要从中提取信息。

文件很大,我只需要提取两个标签之间的信息。

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

我需要提取标签名称和完成之间的信息并将其保存到 txt 文件中。 txt 文件应如下所示:

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

问题在于它解压缩到正确的目标文件夹,但没有将任何内容保存到 result.txt 文件中。我的 txt 文件总是空的。

这是我的代码:

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"

有人可以帮我吗?

【问题讨论】:

  • 这是您实际使用的代码吗?它甚至不运行
  • 您没有将-Path 设置为您的源xml 文档。请参阅Select-Xml 文档。
  • @SEarle1986 是的,它运行,它只是正确提取然后停止
  • 我尝试时失败了。此行存在语法错误,因为您有 ) Select-Xml -XPath '//Report[@finished]').Node.InnerText;

标签: powershell


【解决方案1】:

撇开您的问题的附带方面(似乎从 cmd.exe 调用,尝试传递多行命令字符串,无效的示例 XML,缺少 Select-Xml 的文件参数,缺少对 @ 的输入987654322@ 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

cmd.exe(批处理文件)调用您的 PowerShell 代码,您需要在一行中传递它,或者小心地将其分布在多行中续行,使用^,基于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

如果您需要基础知识方面的帮助,这里有一些 PowerShell 学习资源

【讨论】:

  • 我忘记在 powershell 关键字之后添加"Expand-Archive",但它解压缩了,即使使用您的代码,result.txt 文件仍然是空的
  • @konoha,这适用于您的 XPath 查询未找到任何内容。请注意,您的 XML sn-p 无效,因为某些属性缺少引用。这是一个可行的示例:Select-Xml '//Report[@finished]' -Content '&lt;Report name="result\_many fail" summary="20" yes="19" no="1" finished="20" /&gt;'
  • 另外请注意,如果您真的是从cmd.exe 调用,即使您更正的命令也不起作用,因为如果不使用^ 的续行,您将无法传递多行命令。这个答案中暗示的缺乏输入的问题仍然存在。
  • 是否有任何资源我可以查找以正确执行此操作?真的少了很多吗?
  • 非常感谢!我会阅读文章并尝试理解它们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
  • 2018-11-15
相关资源
最近更新 更多