objFile.DateLastModified返回错误时间,VBS如何获取准确最后写入时间?
VBS获取文件时间与PowerShell结果不符的原因及解决办法
为什么VBS返回的时间不对?
- 路径不匹配:你VBS代码里的
strPandaAVDefinitionPath变量指向的路径,大概率和PowerShell里的C:\ProgramData\Panda Security\Security Protection不是同一个目录。比如变量可能指向了杀毒软件的旧安装路径、或者配置的路径有误,导致读取的是另一个同名的旧文件,自然时间不对。 - FSO缓存或权限限制:Scripting.FileSystemObject(FSO)对某些受系统保护的文件(比如杀毒软件的定义库文件)可能会读取缓存的旧数据,或者因为权限问题无法获取最新的文件元数据。
用VBS获取文件准确最后写入时间的方法
方法1:先确认路径正确性,再用FSO
先把路径写死测试,排除变量路径错误的问题:
Set objFSO = CreateObject("Scripting.FileSystemObject") ' 替换成PowerShell里的正确路径 strTargetFile = "C:\ProgramData\Panda Security\Security Protection\NanoRepository.bin" If objFSO.FileExists(strTargetFile) Then Set objFile = objFSO.GetFile(strTargetFile) WScript.Echo "- NanoRepository.bin最后写入时间: " & objFile.DateLastModified WScript.Echo "- NanoRepository.bin最后访问时间: " & objFile.DateLastAccessed Else WScript.Echo "文件不存在,请检查路径!" End If
方法2:用WMI获取更可靠的文件元数据
WMI直接从系统底层读取文件信息,不受FSO缓存或部分权限限制的影响,结果更准确:
strTargetFile = "C:\ProgramData\Panda Security\Security Protection\NanoRepository.bin" ' 转换路径为WMI要求的格式(把\替换成\\) strWMIPath = Replace(strTargetFile, "\", "\\") Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") ' 查询目标文件的时间属性 Set colFileInfo = objWMIService.ExecQuery( _ "SELECT LastWriteTime, LastAccessTime FROM CIM_DataFile WHERE Name='" & strWMIPath & "'") For Each objFile In colFileInfo ' WMI返回的是UTC格式时间,可根据需要转换成本地时间 WScript.Echo "- 最后写入时间(UTC): " & objFile.LastWriteTime WScript.Echo "- 最后访问时间(UTC): " & objFile.LastAccessTime Next
如果需要把WMI的UTC时间转成本地时间,可以添加以下转换逻辑:
' 将WMI的UTC时间字符串转换为本地时间 Function ConvertWMITimeToLocal(strWMITime) If Len(strWMITime) < 14 Then ConvertWMITimeToLocal = "无效时间" Exit Function End If strYear = Left(strWMITime, 4) strMonth = Mid(strWMITime, 5, 2) strDay = Mid(strWMITime, 7, 2) strHour = Mid(strWMITime, 9, 2) strMinute = Mid(strWMITime, 11, 2) strSecond = Mid(strWMITime, 13, 2) dtUTC = DateSerial(strYear, strMonth, strDay) + TimeSerial(strHour, strMinute, strSecond) ' 转换为本地时间 ConvertWMITimeToLocal = DateAdd("h", DateDiff("h", Now(), dtUTC), Now()) End Function
内容的提问来源于stack exchange,提问作者user29825611
相关产品推荐
相关产品推荐

