You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell新手求助:如何获取日期命名格式的最新目录文件夹

PowerShell按文件夹名称日期获取最新目录

我是PowerShell新手,正在编写脚本,需求是传入项目名称后,在irc_workspace目录中查找特定项目。该目录下的文件夹均以YYYY-MM-DD日期格式命名,我需要根据文件夹名称里的日期获取最新的目录,而非依靠文件的创建/修改/访问时间。例如目录内存在2023-06-19、2023-06-01、2023-05-30等文件夹,需获取2023-06-019文件夹的内容。

我之前尝试通过文件时间属性实现,但不符合需求,相关代码如下:

# Before taking any sync action we need to remove the existing roundtrip folders from workspace and copy the latest roundtrip folder from Server.
$pathToIRCServer = $pathToServer + $argDoorsFsEnd + "\Roundtrips"
$latest = Get-ChildItem $pathToIRCServer | Where { $_.PSIsContainer } | Sort CreationTime -Descending | Select -First 1
$latest.name
'   '
'Replace workspace folders with the latest folder on server.'
Copy-Item -Path $latest -Recurse -Destination $WorkSpaceLocation -Container -Force

后续尝试修改的代码片段:

$pathToIRCServer = $pathToServer + $argDoorsFsEnd + "\Roundtrips"
$latest = Get-ChildItem $pathToIRCServer | Where { $_.PSIsContainer } | Sort CreationTime -Descending | Select -First 1
$latest.name
=============================
$latest = (Get-ChildItem -Path $pathToServerFldr | Sort-Object -Descending -Property LastWriteTime | select -First 1)
$latest_filename = $latest.Name 
=============================
$latest = Get-ChildItem -Path $pathToServerFldr | Sort-Object LastAccessTime -Descending | Select-Object -First 1
#'LatestName: " + $latest.name

正确实现方法

核心思路是将文件夹名称转换为DateTime类型,以此为依据排序,即可筛选出名称日期最新的文件夹:

$pathToIRCServer = Join-Path -Path $pathToServer -ChildPath "$argDoorsFsEnd\Roundtrips"
# 筛选符合日期格式的文件夹,按名称日期排序取最新
$latestFolder = Get-ChildItem -Path $pathToIRCServer -Directory | 
    Where-Object { [DateTime]::TryParseExact($_.Name, 'yyyy-MM-dd', $null, [System.Globalization.DateTimeStyles]::None, [ref]$null) } |
    Sort-Object -Property @{Expression={[DateTime]$_.Name}} -Descending |
    Select-Object -First 1

if ($latestFolder) {
    Write-Host "找到最新日期文件夹: $($latestFolder.Name)"
    Copy-Item -Path $latestFolder.FullName -Recurse -Destination $WorkSpaceLocation -Container -Force
} else {
    Write-Warning "未找到符合YYYY-MM-DD格式的文件夹"
}

代码说明

  • 用Join-Path拼接路径,比直接字符串拼接更安全,避免路径分隔符错误
  • 通过TryParseExact过滤出严格符合yyyy-MM-dd格式的文件夹,排除非日期命名的目录干扰
  • 借助计算属性将文件夹名称转为日期类型,按该值降序排序,取第一个即为最新日期的文件夹
  • 增加存在性判断,未找到目标文件夹时给出明确提示

内容的提问来源于stack exchange,提问作者JenPann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:22:51