本文目录导读:

Windows 批处理脚本
使用 PowerShell
# 修改指定文件夹内所有文件的创建时间为当前时间
$folderPath = "C:\Your\Folder\Path"
Get-ChildItem -Path $folderPath | ForEach-Object {
$_.CreationTime = Get-Date
Write-Host "已修改: $($_.Name)"
}
# 修改为指定时间
$targetTime = Get-Date "2024-01-15 10:30:00"
Get-ChildItem -Path $folderPath | ForEach-Object {
$_.CreationTime = $targetTime
Write-Host "已修改: $($_.Name)"
}
# 仅修改特定类型文件(如.txt)
Get-ChildItem -Path $folderPath -Filter "*.txt" | ForEach-Object {
$_.CreationTime = Get-Date "2024-06-01 08:00:00"
}
使用 CMD(批处理文件)
@echo off
setlocal enabledelayedexpansion
:: 配置参数
set "targetFolder=C:\Your\Folder\Path"
set "targetDate=2024-01-15"
set "targetTime=10:30:00"
echo 正在批量修改文件夹:%targetFolder%
for %%f in ("%targetFolder%\*.*") do (
if exist "%%f" (
echo 修改文件:%%~nxf
copy "%%f"+,,"%%f" >nul 2>&1
)
)
echo 修改完成!
pause
Linux 脚本
使用 touch 命令
#!/bin/bash
# 批量修改文件创建时间为当前时间
target_folder="/path/to/your/folder"
find "$target_folder" -type f -exec touch {} \;
# 修改为指定时间(格式:YYYYMMDDhhmm)
find "$target_folder" -type f -exec touch -t 202401151030 {} \;
# 仅修改特定类型文件
find "$target_folder" -name "*.txt" -type f -exec touch -t 202406010800 {} \;
更详细的 Python 脚本(跨平台)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import time
from datetime import datetime
def batch_modify_creation_time(folder_path, target_time=None, file_ext=None):
"""
批量修改文件创建时间
参数:
folder_path: 文件夹路径
target_time: 目标时间,None则使用当前时间
file_ext: 文件扩展名过滤,如'.txt'
"""
if target_time is None:
target_time = time.time()
else:
target_time = time.mktime(target_time.timetuple())
modified_count = 0
for root, dirs, files in os.walk(folder_path):
for file in files:
if file_ext and not file.endswith(file_ext):
continue
file_path = os.path.join(root, file)
try:
# 获取当前文件状态
stat_info = os.stat(file_path)
# 修改创建时间(在Unix上需要修改atime和mtime,因为ctime不能直接修改)
os.utime(file_path, (target_time, target_time))
print(f"已修改: {file_path}")
modified_count += 1
except Exception as e:
print(f"修改失败 {file_path}: {str(e)}")
print(f"\n共修改 {modified_count} 个文件")
# 使用示例
if __name__ == "__main__":
# 配置参数
folder = "/path/to/your/folder"
# 1. 修改为当前时间
batch_modify_creation_time(folder)
# 2. 修改为指定时间
specified_time = datetime(2024, 1, 15, 10, 30, 0)
batch_modify_creation_time(folder, specified_time)
# 3. 仅修改txt文件
batch_modify_creation_time(folder, specified_time, ".txt")
使用说明
- Windows PowerShell:以管理员身份运行,修改
$folderPath变量 - Linux 脚本:
- 保存为
.sh文件 - 执行
chmod +x script.sh - 运行
./script.sh
- 保存为
- Python 脚本:安装 Python 3,直接运行
注意事项
- ⚠️ 在 Windows 上,批处理只能修改文件修改时间,创建时间需使用 PowerShell
- ⚠️ 在 Linux 上,
ctime(change time)无法直接修改,只能修改atime和mtime - ⚠️ 建议先备份重要文件,或在测试文件夹中先试用
- ⚠️ 某些系统可能限制时间修改权限,需要管理员/root 权限
请根据您的操作系统选择合适的脚本,并先在小范围测试。