You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PowerShell中已复制到目标路径文件的LastWriteTime

PowerShell复制文件后更新目标文件的LastWriteTime为当前时间

你的核心需求是复制文件到目标文件夹后,将目标文件的LastWriteTime更新为当前时间,但原代码里错误地修改了源文件的修改时间,以下是修正和优化后的实现方案:

原代码的核心问题

原代码中$item.LastWriteTime = (Get-Date)这一行操作的是源文件($item是来自C:\Testing\DeviceLists\的文件对象),而非复制到C:\Transfer后的目标文件,完全不符合需求。

修正后的完整代码

$dateStamp = Get-Date -Format "dd-MM-yyyy-dddd HH-mm"
$sourcePath = "C:\Testing\DeviceLists\"
$destPath = "C:\Transfer"
$logPath = Join-Path -Path "C:\Testing\logs\" -ChildPath "Log - $dateStamp.txt"

# 获取目标文件夹中创建时间最晚的文件(用于判断复制条件)
$latestDestFile = Get-ChildItem -Path $destPath -File | Sort-Object -Property CreationTime -Descending | Select-Object -First 1
$compareTime = if ($latestDestFile) { $latestDestFile.LastWriteTime } else { [DateTime]::MinValue }

# 遍历源文件
foreach ($sourceItem in Get-ChildItem -Path $sourcePath -Recurse -File) {
    $sourceLastWrite = $sourceItem.LastWriteTime
    # 判断源文件是否需要复制
    if ($sourceLastWrite -ge $compareTime) {
        $destFullPath = Join-Path -Path $destPath -ChildPath $sourceItem.Name
        # 复制文件
        Copy-Item -Path $sourceItem.FullName -Destination $destFullPath -Force
        # 获取目标文件对象并修改LastWriteTime
        $destItem = Get-Item -Path $destFullPath
        $destItem.LastWriteTime = Get-Date
        # 写入日志
        Add-Content -Path $logPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $($sourceItem.FullName) 已复制,目标文件修改时间已更新"
    }
    else {
        # 写入无需复制的日志
        Add-Content -Path $logPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $($sourceItem.FullName) 修改时间早于目标最晚文件,无需复制"
    }
}

Add-Content -Path $logPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - 所有文件处理完成"

关键优化点说明

  • 修正修改时间的对象:通过Get-Item $destFullPath获取复制后的目标文件对象,再修改它的LastWriteTime,确保操作的是目标文件
  • 完善日志信息:添加时间戳,明确记录每个文件的处理状态,便于后续排查问题
  • 边界处理:如果目标文件夹为空,设置$compareTime为最小时间值,确保所有源文件都会被复制
  • 路径拼接规范:使用Join-Path命令拼接路径,避免手动拼接出现的格式错误

内容的提问来源于stack exchange,提问作者eddeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:40:32