Powershell循环每个文件名仅运行一次文件,即使文件名存在多个扩展名也是如此

问题描述

我将是第一个承认PowerShell不是我的强项的人,但是经过一个晚上的互联网探索之后,我将以下内容拼凑起来。最终目标是通过DateTaken以及大量的sidecar XMP文件来组织大量的图像。它可能不是最优雅的代码,但几乎可以正常工作。

我不知道的最后一个问题是,无论扩展名如何,foreach循环每个文件名仅执行一次。例如,仅处理DSC00001.arw,DSC00001.xmp, DSC00001.jpg。

任何朝着正确方向的观点都会受到赞赏。

谢谢!

$Folders = (Get-ChildItem -Path F:\ -Recurse -Directory -Force).FullName

$objShell  = New-Object -ComObject Shell.Application
$Folders | % {

    $objFolder = $objShell.namespace($_)
    foreach ($File in $objFolder.items()) { 
            if (($File | Split-Path -Extension) -in ".arw",".gif",".tiff",".jpg",".png",".nef") {
                Write-Host $File.Name`t -NoNewline -ForegroundColor Green
                try {
                    $DateTaken = ($objFolder.getDetailsOf($File,12) -replace [char]8206)  -replace [char]8207
                    $DateTaken = [DateTime]::ParseExact($DateTaken,"g",$null)
                    $Year = $DateTaken.ToString('yyyy')
                    $Date = $DateTaken.ToString('yyyy-MM-dd')
                    Write-Host $Date`t -ForegroundColor Blue -NoNewline
                }
                catch {
                    $Year = 'Other'
                    $Date = 'Other'
                    Write-Host $Date`t -ForegroundColor DarkRed -NoNewline
                }
                finally {
                    $DatePath = (Join-Path (Join-Path F:\ $Year ) $Date)
                }
                write-Host $File.Path -> (Join-Path $DatePath ($File | Split-Path -Leaf))-NoNewline
                #Move-Item $File.Path (Join-Path $DatePath ($File | Split-Path -Leaf))
                Write-Host Completed`n -NoNewline

                if (Test-Path (Join-Path ($File | Split-Path) (($File | Split-Path -LeafBase) + '.xmp'))) {
                    Write-Host XMP:`t -ForegroundColor magenta -NoNewLine
                    Write-Host (Join-Path ($File | Split-Path) (($File | Split-Path -LeafBase) + '.xmp')) -> (Join-Path ($DatePath) (($File | Split-Path -LeafBase) + '.xmp'))
                    #Move-Item (Join-Path ($File | Split-Path) (($File | Split-Path -LeafBase) + '.xmp')) (Join-Path ($DatePath) (($File | Split-Path -LeafBase) + '.xmp'))
                }
            }else {
                Write-Host $File.Name is not an image `n -NoNewline -ForegroundColor DarkYellow    
            }
    }

}

解决方法

我不确定为什么$objFolder.items()并没有真正返回所有期望的文件,但是我建议使用PowerShell的内置文件系统提供程序来发现每个文件夹中的实际文件,然后使用{{1} }以获得参考,您可以传递给$objFolder.ParseName()

GetDetailsOf()