如何在Bat脚本的文件名字符串中添加三字母星期缩写?
解决方案
要在fileNameStr末尾添加三字母星期缩写(如SUN、MON等),可以通过以下步骤修改你的批处理脚本:
1. 获取星期数值并映射为缩写
在提取年月日的代码之后,添加获取当前星期数值并映射为大写三字母缩写的逻辑:
:: 获取星期数值(0=周日,1=周一...6=周六) for /f "tokens=2 delims==" %%D in ('"wmic path win32_localtime get dayofweek /value"') do set "dayofweek=%%D" :: 映射星期数值为三字母缩写 set "weekday=" if "%dayofweek%"=="0" set "weekday=SUN" if "%dayofweek%"=="1" set "weekday=MON" if "%dayofweek%"=="2" set "weekday=TUE" if "%dayofweek%"=="3" set "weekday=WED" if "%dayofweek%"=="4" set "weekday=THU" if "%dayofweek%"=="5" set "weekday=FRI" if "%dayofweek%"=="6" set "weekday=SAT"
2. 修改fileNameStr变量
将星期缩写追加到fileNameStr末尾:
set fileNameStr=%year%_%month%_%day%_%weekday%
完整修改后的脚本
@echo off setlocal :: Get the current date and time for /f "tokens=2 delims==" %%I in ('"wmic os get localdatetime /value"') do set "datetime=%%I" :: Extract year, month, and day set "year=%datetime:~0,4%" set "month=%datetime:~4,2%" set "day=%datetime:~6,2%" :: 获取星期数值(0=周日,1=周一...6=周六) for /f "tokens=2 delims==" %%D in ('"wmic path win32_localtime get dayofweek /value"') do set "dayofweek=%%D" :: 映射星期数值为三字母缩写 set "weekday=" if "%dayofweek%"=="0" set "weekday=SUN" if "%dayofweek%"=="1" set "weekday=MON" if "%dayofweek%"=="2" set "weekday=TUE" if "%dayofweek%"=="3" set "weekday=WED" if "%dayofweek%"=="4" set "weekday=THU" if "%dayofweek%"=="5" set "weekday=FRI" if "%dayofweek%"=="6" set "weekday=SAT" :: Convert month number to month abbreviation set "monthname=" if "%month%"=="01" set "monthname=Jan" if "%month%"=="02" set "monthname=Feb" if "%month%"=="03" set "monthname=Mar" if "%month%"=="04" set "monthname=Apr" if "%month%"=="05" set "monthname=May" if "%month%"=="06" set "monthname=Jun" if "%month%"=="07" set "monthname=Jul" if "%month%"=="08" set "monthname=Aug" if "%month%"=="09" set "monthname=Sep" if "%month%"=="10" set "monthname=Oct" if "%month%"=="11" set "monthname=Nov" if "%month%"=="12" set "monthname=Dec" :: Format year to two digits set "year_short=%year:~2,2%" :: Combine into desired format set "formatted_date=%monthname%%day%%year_short%" set fileNameStr=%year%_%month%_%day%_%weekday% :: Define the filename for the downloaded file set OUTPUT_FILE="pdfs\%year%-%month%\%fileNameStr%.pdf"
简化方案(依赖PowerShell)
如果你的系统允许使用PowerShell,可以用一行代码直接获取星期缩写,替换上述的星期数值获取和映射部分:
:: 用PowerShell直接获取大写三字母星期缩写 for /f %%W in ('powershell -Command "(Get-Date).ToString('ddd').ToUpper()"') do set "weekday=%%W"
内容的提问来源于stack exchange,提问作者Tyler Moore
相关产品推荐
相关产品推荐

