Search code examples
datebatch-filewmic

Set date with WMIC (Invalid Verb Switch)


I have revised my question do to comments below pointing me in new directions. I tried date.exe but it fails to set the command in all instances, even with it's returned timestamp.

So I moved on to WMIC. However, I also cannot seem to set the date. But I believe it may be my understanding of WMIC. Can anyone spot any errors in my approach?

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "trail=%dt:~8%" & set "backdt=%dt:~0,8%"
set "targetstamp=20150419%trail%"
echo %targetstamp%
targetstamp
wmic OS Set localdatetime=%targetstamp%
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "ndt=%%a"
set "newtrail=%ndt:~8%"
echo %backdt&&newtrail%
wmic OS Set localdatetime=%backdt%%newtrail%
pause

Solution

  • OK, so you get the current time, replace the date while keeping the time and TZ offset, set that datetime, then do some work right after the wmic os set command, and revert with the then current time.

    Your code is correct. Note that in order to set the date/time via wmic you need to run the command with elevated privileges, like in Windows-Start-"cmd"-right click-"Run as Administrator".

    Edit:
    No, what you see is what cmd.exe leaves behind after treating the Unicode output of wmic. It needs some heavy string pulling to get rid of the extra '\r' in the output.
    This now is running without errors on my PC:

        @echo off
        setlocal
    
        set dt=
        for /f "tokens=*" %%A in ('wmic OS Get localDateTime /value ^| findstr "."') do @set dt=%%A
        set dt=%dt:~14,-1%
        set "trail=%dt:~8%"
        set "saveddt=%dt:~0,8%"
        set targetstamp=20150419%trail%
        wmic OS Set localdatetime=%targetstamp%
    
        REM do some work...
        pause
    
        set dt=
        for /f "tokens=*" %%A in ('wmic OS Get localDateTime /value ^| findstr "."') do @set dt=%%A
        set dt=%dt:~14,-1%
        set "newtrail=%dt:~8%"
        wmic OS Set localdatetime=%saveddt%%newtrail%
    

    Running in a privileged CMD it reports having set the new date. However, nothing changes on my PC - wmic OS set localdatetime just doesn't change the date. YMMV.