我正在编写一个脚本来读取XML文件,例如下面的XMLFILE.XML示例。如果每个任务之前的所有验证都通过了各自的检查,则脚本需要解析每个任务并执行可执行文件及其参数。每个验证标记中的属性执行以下操作:类型告诉脚本它将检查哪些信息,Switch告诉验证某些内容是true还是false。有关正在验证的项目的信息包含在验证元素中。下面的可用空间验证将被解释为"如果C驱动器有200 MB可用空闲继续,则失败。"我遇到的问题是,当我解析XML文件以获得验证时,我立刻得到所有这些,而不是一次得到一个我可以处理的。我非常感谢有关一次解析验证的方法的一些建议。
<?xml version="1.0"?>
<Tasks>
<Task Name="Test task 1">
<Validation Type="Freespace" Switch="True">C|200|MB</Validation>
<Validation Type="Registry Key" Switch="False">HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{342C9BB8-65A0-46DE-AB7A-8031E151AF69}</Validation>
<Validation Type="Registry Value" Switch="False">HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{342C9BB8-65A0-46DE-AB7A-8031E151AF69}|DisplayVersion|4.6.1.20870</Validation>
<Validation Type="Service" Switch="True">ccmexec|running</Validation>
<Executable>notepad.exe</Executable>
<Arguments></Arguments>
</Task>
<Task Name="Test Task 2">
<Validation Type="Registry Key" Switch="False">HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{342C9BB8-65A0-46DE-AB7A-8031E151AF69}</Validation>
<Validation Type="Registry Value" Switch="False">HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{342C9BB8-65A0-46DE-AB7A-8031E151AF69}|DisplayVersion|4.6.1.20870</Validation>
<Validation Type="Service" Switch="True">ccmexec|running</Validation>
<Validation Type="Freespace" Switch="True">C|200|MB</Validation>
<Executable>CMD.EXE</Executable>
<Arguments>/C "ping 127.0.0.1 & EXIT 33"</Arguments>
</Task>
</Tasks>
通常,要读取XML文件并解析其内容,我会执行类似以下操作:
[XML]$XMLALL = Get-Content ".\XMLFILE.XML"
$Tasks = $XMLALL.Tasks
Foreach ($item in $Tasks.Task){
$Name = $item.Name
$Validation = $item.Validation
$Executable = $item.Executable
$Arguments = $item.Arguments
Write-host "`n Task Name: " $Name
Write-host "Validation: " $Validation
Write-host "Executable: " $Executable
}
这给出了以下输出:
任务名称:测试任务1 验证: 可执行文件:notepad.exe
任务名称:测试任务2 验证: 可执行文件:CMD.EXE
答案 0 :(得分:1)
您已经为每个<Task>
节点执行此操作。您只需为每个<Validation>
节点添加另一个循环,如此...
[XML]$XMLALL = Get-Content ".\XMLFILE.XML"
$Tasks = $XMLALL.Tasks
Foreach ($item in $Tasks.Task)
{
$Name = $item.Name
$Executable = $item.Executable
$Arguments = $item.Arguments
Write-host "`n Task Name: " $Name
Write-host "Executable: " $Executable
Write-host $item.Validation.Count " Validations... "
Foreach ($validation in $item.Validation)
{
Write-host "`n Type: " $validation.Type
Write-host " Switch: " $validation.Switch
Write-host " Value: " $validation.InnerText
}
}