Windows shell 触摸特定文件夹的文件夹日期

问题描述 投票:0回答:1

我想运行一个 Windows 脚本,该脚本应该将一个或多个文件夹的日期时间更改为最近的日期时间。它应在每晚午夜通过任务调度程序运行。我需要获取当天且不更早的所有文件夹。

来源:

  • M:\测试\文件夹.1 2024-03-01 16:01
  • M:\测试\文件夹.2 2024-03-02 16:01
  • M:\测试\文件夹.3 2024-03-03 16:01
  • M:\测试\文件夹.4 2024-03-04 16:01
  • M:\测试\Folder.5 2024-03-05 16:01
  • M:\测试\文件夹.6 2024-03-06 16:01
  • M:\测试\Folder.7 2024-03-07 16:01
  • M:\测试\文件夹.8 2024-03-07 16:01
  • M:\测试\Folder.9 2024-03-07 16:01

脚本运行于 2024-03-07 23:59: 后的目标

  • M:\测试\文件夹.1 2024-03-01 16:01
  • M:\测试\文件夹.2 2024-03-02 16:01
  • M:\测试\文件夹.3 2024-03-03 16:01
  • M:\测试\文件夹.4 2024-03-04 16:01
  • M:\测试\Folder.5 2024-03-05 16:01
  • M:\测试\文件夹.6 2024-03-06 16:01
  • M:\测试\文件夹.7 2024-03-07 23:59
  • M:\测试\文件夹.8 2024-03-07 23:59
  • M:\测试\Folder.9 2024-03-07 23:59

有什么想法如何做到这一点吗? 谢谢和亲切的问候 消音器

目前我无法获取今天的文件夹:D

windows shell directory
1个回答
0
投票

尽管您在评论中指出批处理解决方案是首选,但我会建议您参考这个SO答案。引用原作者的话:

我看不到更改日期的简单方法。

重命名或更改属性都不会影响修改日期。

目前,唯一的方法似乎是重命名目录,创建一个新目录,并将内容从旧目录移动到新目录。

这只是一个令人讨厌的解决方案。

因为这是一个令人讨厌的解决方案,而且既然你提到任何脚本都可以,所以我正在使用 Powershell。 # path to check for directories $parentDirectory = "M:\Test\" <# date used is in YYYY-MM-DD format the date below is for testing purposes, use it instead of the original to see it in action # $cutoffDate = "2024-01-01" #> $cutoffDate = Get-Date -Format "yyyy-MM-dd" # test if the path is valid if(-not (Test-Path -Path $parentDirectory) ) { Write-Host Path does not exist Exit } # loop through all the first-level directories # keep only those with desired date Get-ChildItem -Path $parentDirectory -Directory | Foreach-Object { # get the last modified date $directoryModDate = $(Get-Item $_.FullName).lastwritetime # convert it to YYYY-MM-DD $directoryModDate = Get-Date $directoryModDate -Format "yyyy-MM-dd" # compare it to our cutoff date # if it's older, skip it if($directoryModDate -lt $cutoffDate) { # skip it. uncomment the following line to see the skipped ones # Write-Host Skipping $directoryModDate " --- " $cutoffDate return } # not earlier than the cutoff date, we can work with it # uncomment the following line to see the picked up date # Write-Host $directoryModDate $(Get-Item $_.FullName).lastwritetime = $(Get-Date ($cutoffDate + " 23:59:00")); }

请参阅代码中的注释以了解其工作原理。

限制

该脚本有一些限制:

它不是递归的。这意味着它只会处理一级目录,而不会检查其内容。原因是——这并不在你最初的要求中
  • 它不会根据模式对目录名称执行正则表达式匹配。例如,脚本中没有(伪代码)
  • <dir_name> -match "Folder\..*"
  • 。缺少正则表达式名称匹配意味着
    M:\Test\
    中任何具有等于今天日期的
    Date modified
    的目录都将其
    lastwritetime
    更改为
    <today> 23:59:00
    。这一遗漏的原因与前一个相同 - 它不在您最初的请求中
    
    
  • 在真正使用脚本之前,我建议设置一个小测试用例。将代码保存在 *.ps1 文件中,设置测试目录环境,设置计划任务来运行 *.ps1 脚本,然后查看目录的
Date modified

是否已正确更改。

    

© www.soinside.com 2019 - 2024. All rights reserved.