Windows Environmental Variable for Month Year

2020-03-29 06:21发布

问题:

I have a process that writes log files and screenshots to a folder on a regular basis creating between
30-50 files a week. The folder structure is ..\Year\Month\filename.ext, and it cannot be changed.

I'd like to create a shortcut to stick in my Favorites so I can get to this folder quickly but I need a variable for the YEAR and MONTH. Are there an environmental variables for this?

Any bright ideas on how I could create one that updates automatically preferably without a script or scheduled job?

回答1:

The %DATE% environment variable holds the current date. You might be tempted to parse the date with %DATE:~6,4% to get the year.

But this method would not be very solid. %DATE% returns the current date using the windows settings for the "short date format". The problem is that the short date format setting is fully and endlessly customizable. One user can configure its system to show the short date as 29/06/2012; while another user (even in the same system) may choose Fri062912. It's a complete nightmare for a BAT programmer.

One possible solution is to use WMIC, instead. WMIC is the WMI command line interface to WMI. WMI Windows Management Instrumentation is the http://en.wikipedia.org/wiki/Windows_Management_Instrumentation

WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table

returns the date in a convenient way to directly parse it with a FOR.

Completing the parse and putting the pieces together

FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
  SET /A MONTH=%%D
  SET /A YEAR=%%F
)

your shortcut can point to a BAT file that includes the above code and then opens explorer on the right folder.

start "" "D:\FOLDER\%YEAR%\%MONTH%"