gpt4 book ai didi

powershell - 获取格式的创建日期

转载 作者:行者123 更新时间:2023-12-02 23:08:49 26 4
gpt4 key购买 nike

我想遍历图像并将每个图像移动到创建日期的文件夹中,但似乎看不到如何格式化结果日期时间字符串以及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 : The disc was not found. Not disc with name "03/06/2017 07"



这可行,但是需要格式化:
$files[$i].CreationTime

file creation time: 06.03.2017 07:53:21

最佳答案

我们不建议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

关于powershell - 获取格式的创建日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50495802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com