【问题标题】:Copy first image file from subfolders into parent and rename将第一个图像文件从子文件夹复制到父文件夹并重命名
【发布时间】:2019-10-07 22:18:56
【问题描述】:

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

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

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

$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 语句?

【问题讨论】:

  • 文件的.Name 属性是FileName.ext ...因此您无需指定一个。 [咧嘴一笑]

标签: powershell


【解决方案1】:

您在 $root 目录中错误地获取了 $image,因为您使用的 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"

你可以更大胆,因为文件夹的全名包含路径:

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

【讨论】:

  • 非常感谢您向我展示错误并清理代码。现在真的很有意义,并且按预期工作。
猜你喜欢
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
相关资源
最近更新 更多