【问题标题】:Get creation date with format使用格式获取创建日期
【发布时间】:2018-05-23 19:09:17
【问题描述】:

我想遍历图像并将每个图像移动到创建日期的文件夹中,但我似乎没有看到关于如何格式化生成的日期时间字符串以及 ChildItem 的工作原理的要点......

我打算创建一个包含创建日期“2017-03-06”的正确格式字符串的变量,以便我可以创建一个具有该名称的目录并将文件移动到那里。这将在一个循环中发生(forforeach、...)。

$files = Get-ChildItem "P:\photos\"

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName
    Write-Host "file: " $outfile
    $CreationDateStr = Get-ChildItem  $files[$i].CreationTime |
                       Get-Date -f "yyyy-MM-dd"
    Write-Host "file creation time: " $CreationDateStr
}

Read-Host -Prompt "Press Enter to exit"

这样不行,代码不正确:

Get-ChildItem : 未找到光盘。不是名称为“03/06/2017 07”的光盘

这可行,但需要格式化:

$files[$i].CreationTime

文件创建时间:06.03.2017 07:53:21

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我们不推荐Write-Host,因为您无法重定向它。

    这就是我认为您正在寻找的东西:

    Get-ChildItem "P:\Photos" | ForEach-Object {
      $dirName = "{0:yyyy-MM-dd}" -f $_.CreationTime
      if ( -not (Test-Path $dirName -PathType Container) ) {
        [Void] (New-Item $dirName -ItemType Directory)
      }
      Move-Item $_ $dirName -WhatIf
    }
    

    所以在循环中,我们检查指定的目录是否不存在(如果不存在则创建它),然后将文件移动到新目录。如果代码符合您的要求,请删除 -WhatIf

    【讨论】:

    • 完成。我想要一个文件夹中的图像循环并将每个图像移动到创建日期的文件夹中。
    • @MatthiasPospiech 我建议在我的答案中删除您的 cmets,因为它现在已更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多