【问题标题】:How to to use .LastWriteTime and (Get-Date).Month to move data into a new Year/Month Folder Structure如何使用 .LastWriteTime 和 (Get-Date).Month 将数据移动到新的年/月文件夹结构中
【发布时间】:2018-10-11 05:35:19
【问题描述】:

我对 powershell 还很陌生,我的任务是清理存档服务器。我正在尝试创建一个脚本,通过查看它在 Powershell 中的 LastWriteTime 来将文件移动到 Year\Month 文件夹结构中。

我有以下但我不知道如何让它查看文件编辑的月份?

$Path = "D:\Data"
$NewPath = "D:\ArchiveData"
$Year = (Get-Date).Year
$Month = (Get-Date).Month

New-Item $NewPath\ -name $CurrentYear -ItemType Directory
New-Item $NewPath\$Year -Name $Month -ItemType Directory
Get-ChildItem -path $Path | Where-Object {$_.LastWriteTime -Contains (Get-Date).month} | Move-Item -Destination "$NewPath\$Year\$Month"

任何关于我如何做到这一点的想法将不胜感激?

谢谢

【问题讨论】:

    标签: powershell


    【解决方案1】:

    -contains 用于查看数组是否包含项;这里不适合。

    -eq 是您所需要的。根据您的变量$Month,您只需要获取您关心的部分(即月份):

    ($_.LastWriteTime).Month -eq (Get-Date).month
    

    【讨论】:

      【解决方案2】:

      我想我会从另一端处理这个问题。可以在需要时创建目录。

      如果您对正确移动文件感到满意,请从 Move-Item cmdlet 中删除 -WhatIf

      $Path = 'C:\src\t'
      $NewPath = 'C:\src\tarch'
      
      Get-ChildItem -File -Path $Path |
          ForEach-Object {
              $Year = $_.LastWriteTime.Year
              $Month = $_.LastWriteTime.Month
              $ArchDir = "$NewPath\$Year\$Month"
      
              if (-not (Test-Path -Path $ArchDir)) { New-Item -ItemType "directory" -Path $ArchDir | Out-Null }
              Move-Item -Path $_.FullName -Destination $ArchDir -WhatIf
          }
      

      【讨论】:

        猜你喜欢
        • 2012-05-20
        • 1970-01-01
        • 2023-03-08
        • 2018-04-15
        • 2020-04-07
        • 2023-03-18
        • 1970-01-01
        • 2014-02-01
        • 1970-01-01
        相关资源
        最近更新 更多