Windows 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 @   悟透  阅读(1214)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示