2

I wish to read the below xml values for a given key in a secure encrypted manner using powershell.

So, for example, a given key port it should print the value 8814

Likewise for app_name it should print 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>

I tried the below but I get error.

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

Also, wanted to know if this is a secure way [encrypted] to read the key-value?

I will eventually take this to a github actions workflow.

Ashar
  • 2,942
  • 10
  • 58
  • 122

1 Answers1

3

Separate PowerShell CLI (powershell.exe) calls are separate, unrelated sessions, so you cannot create state (define the $xml variable) in one call and expect another to see it.

Instead, use a single call, and let Select-Xml read and query your file directly:

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

Note:

  • As shown, your sample XML isn't valid, because the System.Xml.XmlDocument ([xml]) class apparently requires "yes" - not "true" - as the standalone attribute value.

  • Also, in the XPath query above I've replaced entry with setParameter to match your sample XML.

  • For robustness, the entire -c (-Command) argument (parameter -Command is implied if you omit it)[1] is enclosed in "...", which isn't strictly necessary in this case; however, you do need to escape the " that are part of the PowerShell command either way, as \"


[1] By contrast, pwsh, the PowerShell (Core) CLI, now defaults to -File.

mklement0
  • 382,024
  • 64
  • 607
  • 775