powershell - 使用powershell从xml读取键值

标签 powershell security xml-parsing github-actions key-value

我希望使用 powershell 以安全加密的方式读取给定 key 的以下 xml 值。

因此,例如,给定的键 port 它应该打印值 8814

同样,对于app_name,它应该打印Signup-qa

<?xml version="1.0" standalone="true"?>

<parameters>

<setParameter value="Signup-qa" name="app_name"/>
<setParameter value="8814" name="port"/>
<setParameter value="true" name="debug"/>

</parameters>

我尝试了以下方法,但出现错误。

C:\WINDOWS\system32>powershell # [xml]$xml=Get-Content C:\AMD\setparam.xml

C:\WINDOWS\system32>powershell $xml.SelectSingleNode('//entry[@name="app_name"]').Value
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $xml.SelectSingleNode('//entry[@name=app_name]').Value
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

另外,想知道这是否是读取键值的安全方式[加密]?

我最终会将其引入 github 操作工作流程。

最佳答案

单独的 PowerShell CLI ( powershell.exe ) 调用是单独的、不相关的 session ,因此您无法在一次调用中创建状态(定义 $xml 变量)并期望另一个调用看到它。

相反,使用单个调用,并让 Select-Xml直接读取并查询您的文件:

powershell -c "(Select-Xml -Literalpath C:\AMD\setparam.xml '//setParameter[@name=\"app_name\"]').Node.Value"

注意:

  • 如图所示,您的示例 XML 无效,因为 System.Xml.XmlDocument ([xml]) 类显然需要 "yes" - 而不是 "true" - 作为 standalone 属性值.

  • 此外,在上面的 XPath 查询中,我已将 entry 替换为 setParameter 以匹配您的示例 XML。

  • 为了稳健性,整个 -c (-Command) 参数(参数 -Command隐含的 如果您省略它)[1] 包含在 "..." 中,在本例中这并不是绝对必要的;但是,您确实需要以任何方式转义属于 PowerShell 命令一部分的 ",如 \"


[1] 相比之下,pwsh PowerShell(核心)CLI 现在默认为 -File

关于powershell - 使用powershell从xml读取键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76219807/

相关文章:

powershell - 将 CSV 函数从 Int 更改为 Array

android - 适用于 Android 的基于应用程序的防火墙

javascript - 如何避免 javascript/HTML 元素被篡改

java - 如何检测所需的 XML 属性?

swift 3 : Async queue is still blocking main thread/freezing app?

powershell - Cassandra-Windows 10

json - 从JSON创建CSV文件时Powershell脚本性能不佳

powershell - 在进行 session 后,Get-VM 未被识别为命令

Java http 客户端和 POODLE

jquery - 在 jQuery 中使用 insertAfter()