我有一个类似于以下内容的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<software>
<name>MozillaFirefox</name>
<version>31.3.0</version>
<installer_location>/Mozilla/Firefox/31.3.0.exe</installer_location
</software>
<software>
<name>GoogleChrome</name>
<version>35.7</version>
<installer_location>/Google/Chrome/35.7.msi</installer_location
</software>
<software>
<name>MozillaFirefox</name>
<version>33.4.0</version>
<installer_location>/Mozilla/Firefox/33.4.0.exe</installer_location>
</software>
</catalog>
这是我目前的代码:
#Load XML file into $catalogXML
[xml]$catalogXML = (Get-Content (C:\test.xml))
$softwareList = MozillaFirefox,GoogleChrome,Arduino
$softwareVersionsArray = $catalogXML.catalog.software
$softwareToBeInstalled = $softwareVersionsArray|Group-Object name|ForEach-Object {$_.Group[0]}
哪个输出:
name version installer_location
---- ------- ------------------
MozillaFirefox 31.3.0 /Mozilla/Firefox/31.3.0.exe
GoogleChrome 35.7 /Google/Chrome/35.7.msi
我将编码以搜索$ softwareToBeInstalled中的所有名称,将名称与数组$ softwareList中包含的名称进行比较,并编写$ softwareList中包含但不包含在$ softwareToBeInstalled中的任何软件名称(在我的示例中为Arduino) )到另一个变量$ missingSoftware?
答案 0 :(得分:0)
我会遍历$softwareToBeInstalled
中的名称,并为每个名称检查名称是否包含在数组$softwareList
中。我可能会这样做:
$desiredResults = @()
$softwareToBeInstalled.name.foreach({
if(!$softwareList.contains($_)){$desiredResults += $_})
})
请注意,根据$ softwareToBeInstalled的对象类型,您可能需要调用枚举器才能调用.foreach。您也可以使用:
$softwareToBeInstalled.foreach
使用与上面相同的代码,但引用的是下划线点名而不是下划线。
答案 1 :(得分:0)
创建一个可调整大小的集合,然后检查每个元素是否出现在第二个列表中(如果没有则添加它):
# items can be added to a collection
# this method creates an empty array and pass it to a collection
$missingSoftware = {""}.Invoke()
Foreach($name in $softwareList){
# if doesnt appear
if (-not($softwareToBeInstalled.name.Contains($name))){
# add it to the collection
$missingSoftware.add($name)
}
}
write $missingSoftware