Board logo

标题: [问题求助] 【已解决】求助通过powershell命令从XML中查找指定内容,再进行判断。 [打印本页]

作者: licunwei    时间: 2024-6-24 09:59     标题: 【已解决】求助通过powershell命令从XML中查找指定内容,再进行判断。

本帖最后由 licunwei 于 2024-6-26 11:22 编辑

通过powershell命令查找D:\SCETC\dataXml文件夹下最新的*603.xml文件,再对最新的*603.xml文件内容CardLocalFee和CardLocalPayfee后面的值进行判断,如果值都为0,就新建文件夹D:\交易失败流水\当天日期,并拷贝当前*603.xml文件到当天日期文件夹内。拷贝文件后再循环监测最新的文件。如果值不为0就直接进入循环监测。
xml文件链接地址:https://pan.baidu.com/s/17J3nVIZy62yh_ESjI9ZGpg
提取码:705g

<?xml version="1.0" encoding="UTF-8"?>

-<datas>


-<data>

<attribute value="S000351001004010100202024062213284227" name="id"/>

<attribute value="{"AUTOVC":"0","ActualFeeClass":"0","AutoAxisInfo":"","AutoVLP":"默A00000","AutoVLPC":"9","AxisInfo":"0","AxleNum":"0","BL_Center":"203","BL_SubCenter":"517","CPCExpireTime":"","CPCID":"","CPCIssueOrg":"紫微站","CPCPower":"0","CPCPowerState":"0","CPCStartTime":"","CPCVer":"0","CPUCardId":"1032232480217486","CPUCardSnNo":"1032232480217486","CPUCardType":"2","CPUEndDate":"20331113","CPUIssueID":"路网?","CPUIssuer":"9901","CPUNetID":"9901","CPUStartDate":"20231204","CPUVehicleType":"13","CPUVersion":"69","CPUVlp":"川LD1611","CPUVlpc":"1","CardBal":"0","CardCnt":"0","CardID":"","CardLocalFee":"0","CardLocalPayfee":"0","CardNet":"","CardSN":"0","CardTotalFee":"0","CardTotalPayfee":"0","CardType":"2","DriveAxisConfidience":"0","DriveAxisCount":"0","DriveMaxWeight":"252027642","DriveShaftIndex":"0","DriveShaftNum":"0","DriveVehAxisInfo":"0","DriveVehTranAxleType":"0","ETCtotalAmount":"0","EnAxleNum":"0","EnLane":"","EnLaneType":"0","EnLimit":"0","EnOper":"","EnPSamTerm":"","EnSpTruck":"0","EnStation":"","EnStdVehType":"0","EnTime":"2024-06-22T13:28:00","EnVC":"0","EnVLP":"川A99C2H","EnVLPC":"0","EnVT":"0","EnWasteSN":"0","EnWeight":"0","GBLaneID":"S00035100100401010020","GBStationID":"S0003510010040","HandChioceAxis":"0","HandChioceAxisMenu":"0","InductCnt":"0","KeyVer":"0","LaneAppver":"2.3.6.7","LaneHex":"5101026233","LaneID":"51","LaneRole":"11100000","LaneState":"1","LimitWeight":"-1","LoginTime":"2024-06-22T10:24:55","MonitorTime":"20240622132800","OBUEndDate":"20291230","OBUFeeSumAfter":"0","OBUFeeSumBefore":"0","OBUInfoTypeRead":"-1","OBUInfoTypeWrite":"-1","OBULastGantryHex":"000000","OBULastGantryTime":"1970-01-01T08:00:00","OBUMAC":"0","OBUMileageAfter":"0","OBUMileageBefore":"0","OBUPassState":"2","OBUProvFeeSumAfter":"0","OBUProvFeeSumBefore":"0","OBUProvPayFeeSumAfter":"0","OBUProvPayFeeSumBefore":"0","OBUProvTradeSuccNumAfter":"1","OBUProvTradeSuccNumBefore":"0","OBUSN":"5104884212120482","OBUStartDate":"20191230","OBUState":"94554301","OBUTotalTradeSuccNumAfter":"1","OBUTotalTradeSuccNumBefore":"0","OBUTradeResult":"0","OBUVehicleType":"1","OBUVersion":"67","OBUVlp":"川A99C2H","OBUVlpc":"0","OBUdiscountFeeSumAfter":"0","OBUdiscountFeeSumBefore":"0","OBUpayFeeSumAfter":"0","OBUpayFeeSumBefore":"0","OBUtotalCount":"0","ObuIssueFlag":"四川Q\u0004","OccurTime":"2024-06-22T13:28:00","Oper":"000000999","OperName":"ETC操作员","OverWeightRate":"0","PCRSUVersion":"0","PSAMTradeSN":"00000000","PSamTerm":"215100004ca6","PVC":"0","PVT":"0","ParaVerPreNew":"8420240531009","PayCardBal":"0","PayCardID":"","PayCardNet":"","PayCardTranSN":"0","PreAxisInfo":"","PreAxleNum":"0","PreLimitWeight":"-1","PreOverWeightRate":"0","PreTotalWeight":"-1","QryEnStation":"","RSUManuID":"337","ReleaseTime":"2024-06-22T13:28:42","Shift":"01","StationHex":"51010262","StationID":"262","StdVehType":"0","TAC":"00000000","TotalWeight":"-1","TransType":"09","TriggerTime":"2024-06-22T13:28:42","UnionPayInfo":"","VC":"0","VLP":"川A99C2H","VLPC":"0","VSpeed":"0","VT":"0","Vcnt":"0","VerifyCode":"0","WasteSN":"125","algorithmIdentifier":"1","antennaID":"51","appointId":"","balanceafter":"0","batchNum":"S0003510010040101002020240622102455000000999","bnErrCause":"B409","cardSn":"0","cardVersion":"69","cardfeeSumAfter":"0","cardfeeSumBefore":"0","chargeMode":"1","checkSign":"0","collectFee":"0","consumeTime":"672","description":"0","direction":"1","discountFee":"0","discountFeeGroup":"0","discountType":"","enLaneHex":"5101026233","enStationHex":"51010262","enStdStation":"0","enTollLaneId":"S00035100100401010020","enTollStationId":"0","enTollStationName":"","enlanetype":"3","entime":"2024-06-22T13:28:00","exHeight":"0","exLength":"0","exWidth":"0","fee":"0","feeBoardPlay":"0","feeCalcResult":"0","feeCalcSpecials":"0","feeGroup":"0","feeInfo1":"G:S000351001001910010|T:2024-06-22T13:06:08|ES:51010262|ET:2024-06-22T13:06:08|LG:|LT:|CN:9901|UT:27|AC:6|EAC:6|TT:1|CT:23|PH:b4a84c443136313100000000|PC:1|VT:13|EVT:0|VC:25|FSL:-2291209|WL:0|TW:51400|VSF:0|BH:|PSL:0|RSL:0|SP1:0|MV:20240327002|PV:20240531009|vc:25|vt:16|ac:6|ad:0|R:0,201,0=,0:0 ECODE:0x44000","feeInfo2":"8194","feeInfo3":"5C6313","feeMileage":"0","feeProvBeginHex":"","feeProvInfo":"","feeRate":"0.00","feeSpare1":"0","feeSpare2":"0","feeSpare3":"0","feeSumLocalAfter":"0","feeSumLocalBefore":"0","feeVehicleType":"16","gantryHex":"5C6313","gantryHexOpposite":"5D6313","gantryId":"S000351001001910010","gantryOrderNum":"101","gantryPassCount":"0","gantryPassInfo":"","gantryType":"1","holidayState":"0","hourBatchNo":"S00035100100401010020240622102455000000999","id":"S000351001004010100202024062213284227","identification":"0","interruptSignal":"1","intoTime":"20240622132842.205","invoiceCode":"","invoiceType":"0","lDate":"2024-06-22T00:00:00","laneFLag":"1","laneSign":"1","laneType":"1","lastGantryHex":"000000","lastGantryTime":"2024-06-22T13:28:00","logicalFileCause":"99","mediaNo":"5104884212120482","mediaType":"1","miliSecond":"344","modifyFlag":"1","noCardCount":"0","noCardTimesAfter":"0","noCardTimesBefore":"0","obuDiscountFee":"0","obuId":"5104884212120482","obuPayFee":"0","obuSign":"2","obuTotalAmount":"0","obuTotaldisCountAmount":"0","onLineFee":"0","onLinePayFee":"0","operationMedia":"1","originFee":"0","outofTime":"20240622132842.549","overHeight":"0","overLength":"0","overWidth":"0","paraVer":"2100020240330510002405280143000240113015700020240620150002406210165000506220271600024061401170002021102142000240417018800020072703870002007270366000240622548600024061344700002406225480000240520017700024041801010002404250114000210109011900020102601180002010260223000202403302500023091301240002024053084000000000008420240531009","passId":"019901103223248021748620240622132800","passSign":"2","passState":"2","pathFitFlag":"0","payCardType":"","payFee":"0","payFeeGroup":"0","payOrderNum":"","postBalance":"0","preBalance":"0","provFee":"0","provMinFee":"0","provTransCount":"0","provinceCount":"1","provinceDiscountFee":"0","provinceNumAfter":"1","provinceNumBefore":"0","provinceTransGroup":"0","rateCompute":"2","rateFitCount":"0","readCiphertextVerify":"-1","remarks":"","roadType":"1","serviceType":"1","shortFee":"0","shortFeeMileage":"0","signStatus":"1","spare1":"0","spare2":"0","spcRateVersion":"0","specialType":"42","stationName":"紫微站","supplierID":"0","tac":"00000000","ticketFee":"0","tollIntervalId":"S000351001001910","tollIntervalSign":"1","tollLane":"51","tollLaneId":"51","tollModeVer":"5120240327002","tollParaVer":"5120240531009","tollProvinceId":"510201","tollStation":"000262","tollStationId":"262","tradeReadCiphertext":"0000000000000000","tradeResult":"0","tradeType":"0","tradeWriteCiphertext":"00000000","transCode":"0603","transFee":"0","transFlag":"0","transPayType":"0","transTime":"2024-06-22T13:28:00","unifiedFee":"0","unpayFlag":"0","vehSpeed":"0","vehicleHight":"0","vehicleLength":"0","vehicleSeat":"0","vehicleSign":"0xff","vehicleUserType":"0","vehicleWidth":"0","wGroupID":"0","wLaneType":"3","wasteSpare1":"","wasteSpare4":"0","wasteSpare5":"0"}" name="msg"/>

<attribute value="0603" name="transCode"/>

</data>

</datas>
作者: licunwei    时间: 2024-6-24 21:34

老师些帮帮忙呢
作者: newswan    时间: 2024-6-24 22:24

拷贝文件后再循环监测最新的文件
? 拷贝后,怎么判断最新文件
作者: aloha20200628    时间: 2024-6-24 22:29

本帖最后由 aloha20200628 于 2024-6-25 22:47 编辑

回复 1# licunwei

以下代码存为test.bat运行,其中调用powershell完成最新目标文件的关键字检查,其余均由批处完成...
代码第10行可自定义返回间隔(秒数)假设值=5秒
  1. @echo off &setlocal
  2. set "d=D:\交易失败流水\%date:/=-%"
  3. if not exist "%d%" md "%d%"
  4. :[Loop]
  5. for /f "delims=" %%F in (' dir /b/tw/o-d/a-d "D:\SCETC\dataXml\*603.xml" ') do (set "F=%%~F"&goto[next])
  6. :[next]
  7. set "v=" & for /f %%v in (
  8. 'powershell "$s=gc '%F%' -raw -enc 'utf8';$p1=$s.indexof('CardLocalFee');$p2=$s.indexof('CardLocalPayFee');echo($s[$p1+15]+$s[$p2+18])" ') do (set "v=%%v")
  9. if "%v%"=="00" (copy /y "%F%" "%d%")
  10. timeout /t 5 /NoBreak >nul
  11. goto[Loop]
复制代码

作者: licunwei    时间: 2024-6-25 16:45

回复 3# newswan


    文件夹内会一直新增xml文件,让脚本一直循环监测新增的*603.xml文件。判断*603.xml文件内容2处的值为0,就拷贝当前的*603.xml文件,拷贝完继续监测新增的*603.xml文件。
老师帮忙看看需要怎么写。
作者: newswan    时间: 2024-6-25 20:16

回复 5# licunwei

新增的速度,最小间隔是多少?
试试4楼的
作者: licunwei    时间: 2024-6-25 21:55

回复 6# newswan
4楼的我试了,提取不了xml的内容,快的时候1秒左右生成一个,慢的时候1个小时生成1个,都有可能,时间不固定,需要不停循环监测。
作者: newswan    时间: 2024-6-25 22:22

本帖最后由 newswan 于 2024-6-26 09:00 编辑
  1. $pathSour = "D:\1\"
  2. $pathDest = "D:\2\"
  3. $timeInter = 1
  4. $filexmlLast = ""
  5. while ($True) {
  6. $filexml = Get-ChildItem -Path $pathSour -Filter "*603.xml" | Sort-Object LastWriteTime | Select-Object -Last 1
  7. $filexml = $filexml.FullName
  8. if ( $filexmlLast -ne $filexml ) {
  9. $filexmlLast = $filexml
  10. [xml]$xml = Get-Content -Path $filexml -Encoding "UTF8"
  11. $xml.datas.data.attribute | ForEach-Object {
  12. if ( $_.name -eq "msg" ) { $string = $_.value }
  13. }
  14. if ( $string -match '"CardLocalFee":"0","CardLocalPayfee":"0"' ) {
  15. $path = $pathDest + (Get-Date).ToString("yyyy-MM-dd") + "\"
  16. if ( -not ( Test-Path $path ) ) { New-Item -Type Directory -Path $path }
  17. Write-Host "Copy :  $filexml"
  18. Copy-Item -Path $filexml -Destination $path
  19. }
  20. }
  21. Start-Sleep -Seconds $timeInter
  22. }
复制代码
1秒左右?如果生成时间间隔小于 $timeInter,会拷贝不全
时间间隔过小,会不会浪费性能?
作者: aloha20200628    时间: 2024-6-25 22:51

本帖最后由 aloha20200628 于 2024-6-26 08:07 编辑

回复 7# licunwei

4楼代码已被修正了网页读取编码...
求解本帖的一个关键是 ‘最新网页生成速度’ 与 ‘脚本代码单次检查文件+复制文件的处理速度’ 问题。例如,dir/tw 获取的文件时间戳是秒级精度,若最新网页文件可能在1秒内连续生成 就会有漏网之鱼,如是则须改用别法获取毫秒精度的文件时间戳,还需楼主确认...

作者: Five66    时间: 2024-6-26 10:07

不知行否
  1. $pathSource='D:\SCETC\dataXml'
  2. $pathCopy='D:\交易失败流水'
  3. $fileType='*603.xml'
  4. $matchString='"CardLocalFee":"0","CardLocalPayfee":"0"'
  5. if( -not (Test-Path -LiteralPath $pathSource)){cmd /c pause;exit}
  6. if( -not (Test-Path -LiteralPath $pathCopy)){cmd /c pause;exit}
  7. $fsw=new-object System.IO.FileSystemWatcher
  8. $fsw.path=$pathSource
  9. $fsw.filter=$fileType
  10. $theMain={
  11. if($args.count){
  12. $xmlFile=$args[0]
  13. }else{
  14. $xmlFile=Get-ChildItem -LiteralPath $pathSource -Filter $fileType |Sort {$_.LastWriteTime} |Select -Last 1 -Wait
  15. $xmlFile=$xmlFile.fullname
  16. }
  17. $xmlContent=[xml](Get-Content -LiteralPath $xmlFile -Encoding "UTF8")
  18. $r=$xmlContent.datas.data.attribute.value |foreach{$_ -match $matchString}
  19. if($true -in [object[]]$r){
  20. $thePath=$pathCopy+'\'+(Get-Date).ToString("yyyy-MM-dd")+'\'
  21. if( -not (Test-Path -LiteralPath $thePath)){$null=New-Item -Type Directory -Path $thepath}
  22. write-host "copy $xmlFile to $thePath" -ForegroundColor Green
  23. Copy-Item -LiteralPath $xmlFile -Destination $thePath
  24. }else{write-host "not match , do noting" -ForegroundColor Green}
  25. }
  26. "`n running... `n"
  27. $theMain.invoke()
  28. $whenCreateDo={
  29. $evArgs=$event.SourceEventArgs
  30. $createTime=$event.TimeGenerated
  31. $msg="{0} was {1} at {2}" -f $evArgs.FullPath,$evArgs.ChangeType,$createTime
  32. Write-Host $msg -ForegroundColor Yellow
  33. Start-Sleep -seconds 2
  34. $t=0
  35. while($t -lt 8){
  36. try{
  37. $s=Get-Content -LiteralPath ($evArgs.FullPath) -Encoding "UTF8"
  38. $t=128
  39. }catch{
  40. $t+=2
  41. write-host "open the newfile fail (maybe using) , retry $t seconds later" -ForegroundColor Red
  42. start-sleep -seconds $t
  43. }
  44. }
  45. $theMain.invoke($evArgs.FullPath)
  46. }
  47. Register-ObjectEvent -InputObject $fsw -EventName Created -Action $whenCreateDo -SourceIdentifier fileCreate
  48. if(!$fsw.enableraisingevents){$fsw.enableraisingevents=$true}
  49. "`n press CTRL+C to exit `n"
  50. try{
  51. Wait-Event -SourceIdentifier fileCreate
  52. }finally{
  53. $fsw.enableraisingevents=$false
  54. Unregister-Event -SourceIdentifier fileCreate
  55. $fsw.dispose()
  56. "`n done `n"
  57. cmd /c pause
  58. }
复制代码

作者: licunwei    时间: 2024-6-26 11:18

回复 10# Five66


    完美 ,谢谢老师。
作者: aloha20200628    时间: 2024-6-27 11:12

本帖最后由 aloha20200628 于 2024-6-27 12:09 编辑

回复 7# licunwei

用批处拿下此帖是个有趣的练习,订正4楼代码如下...
关键是要调整算法流程》为了规避最新网页文件生成速度的问题,不是仅盯第一个最新文件F1而是顺序检查F1及其后一组连续生成的文件,直到遭遇上一轮检过的第一个文件为止,如此可确保每次轮检无一漏网。检查文件关键词改用系统内置的findstr.exe,因所匹配关键词均为ascii字符数据,故无须处理文件编码问题,而且批处调用findstr明显快过powershell。
  1. @echo off &setlocal
  2. set "d=D:\交易失败流水\%date%"
  3. if not exist "%d%" md "%d%"
  4. pushd "D:\SCETC\dataXml\"
  5. :[Loop]
  6. for /f "delims=" %%F in (' dir /b/tw/o-d/a-d "*603.xml" ') do (
  7. if not defined _lastF set "_lastF=%%F"
  8. if defined lastF if /i "%%F"=="%lastF%" goto[next]
  9. findstr /i "\"CardLocalFee\":\"0\",\"CardLocalPayfee\":\"0\"" "%%F">nul&&(copy /y "%%F" "%d%")
  10. )
  11. :[next]
  12. set "lastF=%_lastF%" &set "_lastF="
  13. timeout /t 3 /nobreak>nul
  14. goto[Loop]
复制代码

作者: 77七    时间: 2024-6-27 12:17

新增的文件仍保留在原目录,1秒一个,1天8万多秒,应该会拉低代码效率吧。不妨把处理完的文件移走,然后就是查找关键词耗点时间,应该效率很高。
作者: 77七    时间: 2024-6-27 14:54

  1. @echo off
  2. rem 保存为ansi,删除第15行中的|
  3. set "f=d:\另存"
  4. cd /d "D:\SCETC\dataXml\"
  5. md "%f%" 2>nul
  6. :loop
  7. for /f "tokens=1-3 delims=/ " %%a in ("%date%") do (
  8. set d=d:\交易失败流水\%%a%%b%%c
  9. )
  10. md "%d%" 2>nul
  11. for /f "delims=" %%i in ('2^>nul dir /b /a-d "*603.xml"') do (
  12. find "CardLocalFee&|quot;:&|quot;0&|quot;,&|quot;CardLocalPayfee&|quot;:&|quot;0&|quot;" "%%i" 1>nul && copy "%%i" "%d%\"
  13. move "%%i" "%f%\"
  14. )
  15. timeout 1 >nul
  16. goto :loop
复制代码





欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2