首页 > 解决方案 > 将第一个图像文件从子文件夹复制到父文件夹并重命名

问题描述

在一个特定的文件夹中,我有几个子文件夹,每个子文件夹中都存储了图像文件。

我想将每个子文件夹中的第一个图像文件复制到父文件夹中,并将其重命名为它所属的文件夹名称。

我设法用网站上其他几个问题的信息编写了以下脚本,但有些东西没有按预期工作。运行脚本不会复制/重命名任何文件。

$Root = (Get-Item -Path '.\' -Verbose).FullName                                        #'

$Folders = Get-ChildItem -Path $Root -Directory

$Image = Get-ChildItem -Name -Filter *.* | Select-Object -First 1

Foreach($Fld in $Folders)
{
    Copy-Item -Path "$($Fld.FullName)\$Image" -Destination "$Root\$($Fld.Name).jpeg"
}

Read-Host -Prompt "Press Enter to exit"

我希望能够从任何文件夹运行脚本,路径必须是相对的,而不是绝对/硬编码的。我认为这个$Root变量达到了这个目的。

子文件夹仅包含图像文件,其中的过滤器*.*可以$Image Get-ChildItem用于此目的,因为它总是会选择图像。但是 Copy-Item 命令将使用 jpeg 扩展名复制它,是否可以检查图像文件扩展名并相应地复制/重命名?也许有一些 If 语句?

标签: powershell

解决方案


您错误地$image在您的$root-directory 中获取了,因为您使用的是get-childitem没有任何-Path参数的。为了您的目的,您需要Foreach $Fld(文件夹)单独:

$Root = (Get-Item -Path '.\' -Verbose).FullName                                        #'

$Folders = Get-ChildItem -Path $Root -Directory

Foreach($Fld in $Folders)
{
    $Image = Get-ChildItem -Path $Fld -Name -Filter *.* | Select-Object -First 1

    Copy-Item -Path "$($Fld.FullName)\$Image" -Destination "$Root\$($Fld.Name).jpeg"
}

Read-Host -Prompt "Press Enter to exit"

这是你的代码有点缩短:

$Folders = Get-ChildItem -Directory # Without -path you are in the current working directory

Foreach($Fld in $Folders)
{
    $Image = Get-ChildItem -Path $Fld -Filter *.* | Select-Object -First 1    # Without the -name you get the whole fileinfo

    Copy-Item -Path $Image.FullName -Destination "$PWD\$($Fld.Name)$($Image.Extension)"    # $PWD is a systemvariable for the current working directory
}

Read-Host -Prompt "Press Enter to exit"

您甚至可以更大胆,因为文件夹的 FullName 包含路径:

Copy-Item -Path $Image.FullName -Destination "$($Fld.FullName)$($Image.Extension)"

推荐阅读