有时为了需要会修改文件时间戳,通常是先修改系统时间,然后再保存文件。这样做麻烦不说,还有可能会影响到其他依赖日期的应用程序。
今天制作了一个Powershell脚本,可以很好处理这个问题,不用修改系统时间,直接给出要修改的路径和指定的时间即可。
使用Notepad++写入下面代码内容,保存为SetTime.ps1 文件。保存时确保编码是 UTF-8 with BOM。
<#
.SYNOPSIS
循环交互式修改文件或文件夹的时间戳。
.DESCRIPTION
支持修改创建时间、修改时间和访问时间。
#>
# 清理屏幕
Clear-Host
# 使用 while($true) 开启无限循环
while ($true) {
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host " Windows 时间戳修改工具" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "提示: 输入 exit 可以退出脚本" -ForegroundColor Magenta
# 1. 获取路径
$targetPath = Read-Host "请输入文件或文件夹的完整路径"
$targetPath = $targetPath.Trim('"').Trim("'")
# 检查用户是否想要退出
if ($targetPath -eq "exit") {
break
}
# 如果路径为空,直接重新开始循环
if ([string]::IsNullOrWhiteSpace($targetPath)) {
Write-Host "[提示] 路径不能为空!" -ForegroundColor Yellow
continue
}
# 检查路径是否存在,不存在则跳回开头
if (-not (Test-Path -Path $targetPath)) {
Write-Host "[错误] 找不到指定的路径,请检查路径是否正确!" -ForegroundColor Red
continue
}
# 2. 获取时间
$timeString = Read-Host "请输入目标时间 (格式: 2026-02-14 14:30:00)"
if ($timeString -eq "exit") {
break
}
try {
$newTime = Get-Date $timeString
} catch {
Write-Host "[错误] 时间格式不正确!请使用 YYYY-MM-DD HH:MM:SS 格式。" -ForegroundColor Red
continue
}
# 3. 修改时间戳
try {
$item = Get-Item $targetPath
$item.CreationTime = $newTime
$item.LastWriteTime = $newTime
$item.LastAccessTime = $newTime
Write-Host "[成功] 已将时间戳成功修改为: $newTime" -ForegroundColor Green
} catch {
Write-Host "[错误] 修改失败,请检查文件是否被占用或缺少管理员权限。" -ForegroundColor Red
}
# 执行完后,会自动回到循环开头,无需手动按回车
}
Write-Host "`n脚本已退出。" -ForegroundColor Gray
使用时用右键点击它,选择 使用 PowerShell 运行 (Run with PowerShell)。
如果系统提示“禁止执行脚本”,请按以下步骤解除限制:
- 点击开始菜单,搜索
PowerShell,右键选择以管理员身份运行。 - 输入以下命令并按回车:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
- 出现提示时输入
Y并回车。 - 之后就可以运行任何自己编写的
.ps1脚本了。