我对PowerShell很新, 我想创建一个脚本来监视正在创建的xml文件的文件夹。 如果在xml中找到某个元素值,我希望脚本执行一个简单的任务。 这是一个xml的例子:
<?xml version="1.0" encoding="ISO-8859-1"?>
<recognitionevent>
<eventnumber>7457</eventnumber>
<checkpoint>2</checkpoint>
<speed>0</speed>
<length>0</length>
<stringdata>Checkpoint 2</stringdata>
<pin/>
<rfid/>
<carddata/>
<unitdetected>0</unitdetected>
<trailerdetected>0</trailerdetected>
<date>
<year>2018</year>
<month>03</month>
<day>05</day>
<hour>18</hour>
<minute>40</minute>
<second>51</second>
</date>
<frontlicenseplates>
<licenseplate>
<unformatted>9224026</unformatted>
<formatted>9224026</formatted>
<nationality>ISR</nationality>
<confidence>0.993321</confidence>
<timestamp>20180305184052135</timestamp>
<imagefile>C:\Program Files\DynamTech\Images\Visy\2018\03\05\18\20180305184051_2_7457_Front23.jpg</imagefile>
</licenseplate>
</frontlicenseplates>
</recognitionevent>
这是脚本
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\source"
$watcher.Filter = "*.xml*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$action = { $path = $Event.SourceEventArgs.FullPath
$xml = [xml](get-content $Path)
$checkpoint = $xml.recognitionevent | Select checkpoint
$licenseplate = $xml.recognitionevent.frontlicenseplates.licenseplate | Select formatted
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$licenseplate, $checkpoint"
Add-content "C:\Users\bill\Documents\Script\log.txt" -Value $logline
}
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 1}
可行,但会返回 $ checkpoint 和 $ licenseplate 的值 如 @ {checkpoint = 2} 和 @ {licenseplate = 9224026}
我不知道为什么会这样。我想在 if 语句中使用它,如:
If ($checkpoint -eq 2)
{
$command = @'
cmd.exe /C powershell.exe -ExecutionPolicy Bypass -file C:\Users\bill\Documents\Script\arduino.ps1 COM5 9600 0
'@
Invoke-Expression -Command:$command
}
但我不能
答案 0 :(得分:0)
尝试这样的事情:
$checkpoint = $xml.recognitionevent.checkpoint
$licenseplate = $xml.recognitionevent.frontlicenseplates.licenseplate.formatted