【问题标题】:Powershell: XML import doesn't pass the values from XMLPowershell:XML 导入不传递来自 XML 的值
【发布时间】:2020-06-05 13:43:51
【问题描述】:

尝试从 Xml 导入值

<configuration>
<properties>
<subtype type="integer">1</subtype>
<name type="string">packer-centos8-base-g2-10</name>
</properties>
<settings>
<processors>
<count type="integer">4</count>
</processors>
<memory>
<bank>
<dynamic_memory_enabled type="bool">False</dynamic_memory_enabled>
<limit type="integer">1048576</limit>
<reservation type="integer">512</reservation>
<size type="integer">4096</size>
</bank>
</memory>
</settings>
<AltSwitchName type="string">Default Switch</AltSwitchName>
<boot>
<device0 type="string">Optical</device0>
</boot>
<secure_boot_enabled type="bool">False</secure_boot_enabled>
<notes type="string"> </notes>
<vm-controllers>
<scsi ChannelInstanceGuid="x">
<controller0>
<drive0>
<pathname type="string">
C:\San\SV65\hyper-packer\hyper-packer\hyperv314337150\packer-centos8-base-g2-10.vhdx
</pathname>
<type type="string">VHD</type>
</drive0>
</controller0>
</scsi>
</vm-controllers>
</configuration>

Powershell 命令的输出

PS C:\San\SV65\ps> $jvariables=Get-Content -Raw -Path '.\variables-ps.json' | ConvertFrom-Json
PS C:\San\SV65\ps> $VMXml = Get-ChildItem -path $jvariables.vmfp -recurse -include *.xml

PS C:\San\SV65\ps> write-host $jvariables.vmfp

C:\San\SV65\hyper-packer\hyper-packer\output-centos8-10\Virtual Machines\

PS C:\San\SV65\ps> write-host $VMXml

C:\San\SV65\hyper-packer\hyper-packer\output-centos8-10\Virtual Machines\box.xml

PS C:\San\SV65\ps> write-host $VMbox

PS C:\San\SV65\ps>

$VMbox 得到一个空值,我正在尝试从 xml 中提取一个值

 $name = $VMbox.configuration.properties.name

这是因为 btn "Virtual Machines" 中的空格吗?在 $VMXml 中?

如果它是从 variables.json 填充的

$jvariables=Get-Content -Raw -Path '.\variables-ps.json' | ConvertFrom-Json

{
"psfp":  "C:\\San\\SV65\\ps\\",
"vmfp": "C:\\San\\SV65\\hyper-packer\\hyper-packer\\output-centos8-10\\Virtual Machines\\",
"psmp": "C:\\San\\SV65\\ps\\",
"vmname": ""
} 

如何将变量中的值添加为这种格式的'value'?

即使我添加,它也不会在 powershell 中执行。

总而言之,我想从json中提取路径并尝试从xml中获取值并在代码中使用。

【问题讨论】:

标签: json xml powershell


【解决方案1】:

在变量$VMXml中获取路径后忘记加载xml文件。
此外,很可能/很可能通过使用

$VMXml = Get-ChildItem -path $jvariables.vmfp -recurse -include *.xml

这个变量包含一个 array FileInfo 和/或 DirectoryInfo 对象,所以最好使用类似

$VMXml = Get-ChildItem -Path $jvariables.vmfp -Recurse -Filter '*.xml' -File | Select-Object -First 1

只获取一个 FileInfo 对象。

然后使用实例化变量$VMbox

[xml]$VMbox = Get-Content -Path $VMXml.FullName

并使用您的代码$name = $VMbox.configuration.properties.name从中获取值

希望有帮助

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 2018-10-08
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多