powershell - 将第一个图像文件从子文件夹复制到父文件夹并重命名
问题描述
在一个特定的文件夹中,我有几个子文件夹,每个子文件夹中都存储了图像文件。
我想将每个子文件夹中的第一个图像文件复制到父文件夹中,并将其重命名为它所属的文件夹名称。
我设法用网站上其他几个问题的信息编写了以下脚本,但有些东西没有按预期工作。运行脚本不会复制/重命名任何文件。
$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 语句?
解决方案
您错误地$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)"
推荐阅读
- python - 无法将来自 Windows 客户端的工件记录到在 GCP VM 实例上运行的 mlflow 服务器
- apache-flink - 如果 flink 的 keyBy 运算符被赋予不同的键,然后是翻转窗口,会发生什么
- python-3.x - 如何将字典的值从列表类型更改为字符串类型
- scrapy - 用于scrapy的Pycharm ideolog
- amazon-web-services - AWS DAX 中的访问被拒绝异常
- oracle - 如何避免 OR 扩展?
- vue.js - 在 b-form 中使用 Vue Validate 滚动到第一个错误
- react-native - 初始化 react-native-twitter-signin 时出现异常
- r - ggplot2散点图添加自定义置信区间带线;类似于 abline() 方法
- python - 有一个特殊的网页找不到任何元素