Windows 11 bat批处理+PowerShell获取文件日期 和 时分秒

前言全局说明

Windows bat批处理+PowerShell获取文件秒


一、说明

PowerShell 是 Win 7 开始才有的,低于这个版本系统可能用不了


二、分开获取 日期 和 时分秒

获取bat文件自身的日期时间 和 时分秒

1.源码

文件名:get-file-second.bat

@echo off
chcp 65001>nul
echo.
echo.
set bak_file=get-file-second.bat

:: 获取文件修改时间
setlocal
set file="C:\path\to\file.txt"
for %%a in (%bak_file%) do (
    for /f "tokens=1-3 delims=:. " %%b in ('powershell "(Get-Item '%%~fa').LastWriteTime.ToString('HH:mm:ss')"') do (
        set hh=%%b
        set min=%%c
        set sec=%%d
    )
)
echo 文件的最后修改时间是:%hh%:%min%:%sec%

for %%a in (%bak_file%) do (
    for /f "tokens=1-3 delims=-/ " %%b in ('powershell "(Get-Item '%%~fa').LastWriteTime.ToString('yyyy-MM-dd')"') do (
        set year=%%b
        set m=%%c
        set d=%%d
    )
)
echo 文件的最后修改日期是:%year%-%m%-%d%
endlocal
echo.
pause

tokens 是获取拆分的长度
delims 分割字符的符号,注意里面有空格

chcp 65001 是文件编码,适用于 Win 11 ,
如果 Win7 老系统可以改成 Chcp 936

2.执行命令

.\get-file-second.bat

3.结果

image

image


三、合并获取 日期 和 时分秒

获取bat文件自身的日期时间 和 时分秒

1.源码

文件名:get-file-second.bat

@echo off
chcp 65001>nul
set bak_file=get-file-second_1.bat 

:: 获取文件修改时间
setlocal
for %%a in (%bak_file%) do (
    for /f "tokens=1-6 delims=:.-/ " %%b in ('powershell "(Get-Item '%%~fa').LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')"') do (
        set year=%%b
        set month=%%c
        set day=%%d
        set hour=%%e
        set minute=%%f
        set second=%%g
    )
)
echo 文件的最后修改时间是:%year%-%month%-%day%   %hour%:%minute%:%second%
endlocal

echo.
pause

2.执行命令

.\get-file-second.bat

3.结果

image

image


四、日期 “年” 长度

1.源码

把上面

ToString('yyyy-MM-dd')

改成

ToString('yy-MM-dd')

2.执行命令

.\get-file-second.bat

3.结果

2024 只显示后两位 24
image


五、日期 “月” 长度

获取个位数的月份

1.源码

.ToString('yyyy-MM-dd')

改成

.ToString('')

2.执行命令

.\get-file-second.bat

3.结果

2月前不带 0 了
image



免责声明:本号所涉及内容仅供安全研究与教学使用,如出现其他风险,后果自负。




参考、来源:
chatGPT
https://cloud.tencent.com/developer/ask/sof/100684771



posted @ 2024-02-21 10:34  悟透  阅读(1619)  评论(0)    收藏  举报