我有一个XML文件,如下所示:
<Feature>
<B7>A</B7>
<B8>B</B8>
<B9>C</B9>
<ExitCode>
<Found>123</Found>
<NotFound>789</NotFound>
</ExitCode>
</Feature>
我有一个PowerShell脚本看起来像这样:
$regex = [regex]$Pattern
$matching = $regex.Match($FB)
if ($matching.Success) {
while ($matching.Success) {
"Match found: {0}" -f $matching.Value
exit 123 #I want to delete this
$matching = $matching.NextMatch()
}
} else {
"Not Found"
exit 789 #I want to delete this
}
我想得到exitcode,但我不想写exit 123
和exit 780
,我只是想从XML文件调用退出代码,所以每次我想改变exitcode号,我只是从XML文件修改,而不是从PowerShell脚本。
所以,如果我使用批处理文件运行脚本,我可以获取exitcode日志,如下所示:
set log=C:\Users\Log.txt
set PS=C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
set PS=%PS%\powershell.exe -ExecutionPolicy Bypass -File
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass -File C:\Users\XML.ps1 -i C:\Users\Feature.txt -j C:\Users\XML.xml
echo %ERRORLEVEL% > "%log%"
像这样的东西;读取XML文件,然后通过属性引用从中获取数字:
$xmlData = New-Object -TypeName System.Xml.XmlDocument
$xmlData.Load('c:\test\data.xml')
$regex = [regex]$Pattern
$matching = $regex.Match($FB)
if ($matching.Success) {
while ($matching.Success) {
"Match found: {0}" -f $matching.Value
exit $xmlData.Feature.ExitCode.Found
$matching = $matching.NextMatch()
}
} else {
"Not Found"
exit $xmlData.Feature.ExitCode.NotFound
}
编辑:更新以获得更好的XML处理,可以正确处理XML文件编码。感谢@ tomalak的评论。