在一个特定的文件夹中,我有几个子文件夹,每个子文件夹中都存储有图像文件。
我想将每个子文件夹中的第一个图像文件复制到父文件夹中,并将其重命名为它所属的文件夹的名称。
我设法将以下脚本与网站上其他几个问题的信息一起编写,但是有些东西无法正常工作。运行脚本不会复制/重命名任何文件。
$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
因为使用的是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)"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句