-->

Compare file creation dates from the command promp

2019-08-12 19:22发布

问题:

At my university, we use VMware quite extensively to allow experimentation of admin tasks on otherwise heavily locked down computers. I use the same VM's at home so I don't have to worry about the cluttered environment of my native PC, by copying it to and from my USB flash drive.

The VM I use is snapshot'd with all the settings I like, and set to revert to snapshot on shutdown, so ideally it never changes. As I use multiple computers, I have a script that checks if the VM is present, and if not, copies it over and schedules an auto-open on next login.

My current script looks like this:

@echo off

if exist "C:\Users\[Username]\Desktop\Win7x86\Win7x86.vmx" goto open
if not exist "C:\Users\[Username]\Desktop\Win7x86\Win7x86.vmx" echo VM files not found, preparing to copy from USB
goto usb

:usb
if exist "F:" goto copy
if not exist "F:" echo Please insert USB drive.
pause
goto usb

:copy
robocopy "F:\Virtual Machines\Win7x86" "C:\Users\[Username]\Desktop\Win7x86" /mir /eta
schtasks /create /ru [Username] /rp [Password] /xml "%cd%\Win7x86 Opener.xml" /tn "Win7x86 Opener"
goto open

:open
PATH "%PROGRAMFILES%\VMware\VMware Workstation\"
START vmware.exe -x "C:\Users\[Username]\Desktop\Win7x86\Win7x86.vmx"

My problem is this; sometimes I make change to the VM, and update the snapshot.

I want my script to compare the creation dates of the source files (USB) to the local files (desktop). If the local are newer, then obviously it's been copied since the last update and is fine to run, but if the source files are newer, then the local needs updating.

I plan on using vmware.log as the comparison file as it's small and retains it's creation date (some VM files are deleted and re-created during the VM running process).

I've scoured the internet and the best I found compared dates and listed the newest; but with my very limited batch scripting knowledge, I have no idea how to pipe a robocopy command off that output.

回答1:

This should do it.

@echo off

for /f "tokens=* usebackq" %%d in (`wmic datafile where Name^="C:\\Users\\[Username]\\Desktop\\Win7x86\\vmware.log" get creationdate ^| findstr ^"[0-9]^"`) do ( set tmpd=%%d )
set vmlocaldate=%tmpd:~0,8%

for /f "tokens=* usebackq" %%d in (`wmic datafile where Name^="F:\\Virtual Machines\\Win7x86\\vmware.log" get creationdate ^| findstr ^"[0-9]^"`) do ( set tmpd=%%d )
set vmusbdate=%tmpd:~0,8%

if %vmusbdate% gtr %vmlocaldate% goto copy

I don't know how this will fit into your script as it will need the USB drive plugged in; at the moment you can launch your and it will straight away open the local virtual machine if it exists, you have to decide if you always need to plug the USB drive in and check the creation date, if you only want to check when if the USB happens to be present, or change your USB prompt to allow you to skip plugging the drive in.

NB. It is significantly easier in both VBScript and PowerShell.