如何修改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
相关产品推荐
相关产品推荐

