Powershell 在目录名格式为YYYY-MM-DD的目录中获取扩展名为.JPG的文件

Powershell 在目录名格式为YYYY-MM-DD的目录中获取扩展名为.JPG的文件,powershell,Powershell,我想获取当前目录和所有子目录中的所有.JPG文件,其中目录名为YYYY-MM-DD格式。 i、 e D:\Pictures\2018-01-01\DSC_0001.JPG你差点就拿到了 $testFiles = Get-ChildItem -Path $srcFolder -Recurse -Filter *.JPG | Where-Object { (Split-Path (Split-Path $_.FullName -Parent) -Leaf) -match '^\d{4}-\d{2}

我想获取当前目录和所有子目录中的所有.JPG文件,其中目录名为
YYYY-MM-DD
格式。 i、 e

D:\Pictures\2018-01-01\DSC_0001.JPG你差点就拿到了

$testFiles = Get-ChildItem -Path $srcFolder -Recurse -Filter *.JPG 
| Where-Object { (Split-Path (Split-Path $_.FullName -Parent) -Leaf) -match '^\d{4}-\d{2}-\d{2}$' }

您需要使用
$设置路径。当
$通过整个对象时,Fullname

我不确定您使用嵌套拆分路径做什么,但在我的测试中它不起作用

这是有效的,并且可能满足您的需求:

gci *.jpg -Recurse | ? { $_.FullName -match '\\\d{4}-\d{2}-\d{2}\\' }`

下面是一种稍微不同的获取文件列表的方法。[grin]它针对文件的
.Directory
属性进行测试

_[编辑-原始版本与整个目录名匹配,但无法获取仅包含日期模式的目录名。]

$SourceDir = $env:temp
$Filter = '*.log'
# this pattern will give embedded date patterns
#$DirPattern = '\d{4}-\d{2}-\d{2}'
# this pattern gives ONLY a date pattern
$DirPattern = '^\d{4}-\d{2}-\d{2}$'

$GCI_Params = @{
     LiteralPath = $SourceDir
     Filter = $Filter
     File = $True
     Recurse = $True
    }
$FileList = Get-ChildItem @GCI_Params |
    # this matches against the entire directory
    #Where-Object {$_.Directory -match $DirPattern}
    # this one correctly filters against only the parent dir
    Where-Object {(Split-Path -Path $_.DirectoryName -Leaf) -match $DirPattern}

$FileList.Count

在我的系统上,此时,它返回~~67~~
54
作为匹配文件的计数

这不匹配任何包含在反斜杠字符中的日期模式吗?OP似乎只想匹配父目录,而不是它上面的任何内容。@Lee_Dailey更正Lee,只是父目录名。@ChadRichardson-i thot so。。。但还是弄错了。[咧嘴笑]现在修好了。。。谢谢你的提醒!我知道这个问题与链接问题的重复性并不明显,但归结起来就是(a)PowerShell cmdlet遗憾地将文件/目录路径参数绑定为字符串,而不是文件系统信息对象,以及(b)文件系统信息对象字符串化不一致。这是一个有效的解决方案,但需要明确的是:在PowerShell中传递对象应该是一种优势,而不是一种责任:PowerShell中的所有cmdlet都应该可靠地接受文件系统信息对象而不是路径字符串,然而,遗憾的是,(a)它们只接受路径字符串,(b)是问题的根源。另请参见:这是可行的,但它会搜索模式的完整路径,我只希望它只搜索文件的父目录,而不是完整路径。我也只想让它找到那些只是
YYYY-MM-DD
的文件夹,这样
yyy-MM-DD卡盘的BDay Party
就不匹配了。我认为该部分只是在调整模式regex,但仅父目录名搜索将无法与$目录一起工作,因此使用嵌套的
分割路径
解决方案。如果有更好的方法只获取父目录名,而不是完整路径,我非常欢迎:)@ChadRichardson-arg!出于某种原因,我认为这只是看到父目录名,而不是整个目录名。[blush]您认为满足您的需求需要某种拆分和分隔符测试,这是正确的。你认为我应该修改答案以包含这些内容吗?谢谢李,我已经接受了另一个答案,而且它是有效的,所以你不需要在这方面再浪费时间,但我感谢你的输入。@ChadRichardson-我想我会用注释来修复它-只是为了避免让任何人困惑。感谢您指出问题所在![咧嘴笑]
$SourceDir = $env:temp
$Filter = '*.log'
# this pattern will give embedded date patterns
#$DirPattern = '\d{4}-\d{2}-\d{2}'
# this pattern gives ONLY a date pattern
$DirPattern = '^\d{4}-\d{2}-\d{2}$'

$GCI_Params = @{
     LiteralPath = $SourceDir
     Filter = $Filter
     File = $True
     Recurse = $True
    }
$FileList = Get-ChildItem @GCI_Params |
    # this matches against the entire directory
    #Where-Object {$_.Directory -match $DirPattern}
    # this one correctly filters against only the parent dir
    Where-Object {(Split-Path -Path $_.DirectoryName -Leaf) -match $DirPattern}

$FileList.Count