【问题标题】:PowerShell script to copy jpg files from one folder to another by creating two subfolders with the same namePowerShell 脚本通过创建两个同名的子文件夹将 jpg 文件从一个文件夹复制到另一个文件夹
【发布时间】:2021-08-21 19:49:19
【问题描述】:

我需要一些帮助,我是 PowerShell 的新手,我正在尝试使用它来简化我的一些工作。我正在编写一个 PowerShell 脚本来从一个位置 (C:\Pictures\People\People) 复制 JPG 文件并将它们移动到一个新位置。

问题是我需要在这个新位置创建一个与 JPG 同名的文件夹,然后再创建一个与 JPG 同名的子文件夹。

所以我需要将图像从 C:\Pictures\People\People 移动到 C:\Pictures\JPG_Name\JPG_Name\'JPG_Image' ,我将调用 JPG_Image 到 C:\Pictures\JPG_Name\JPG_Name\'JPG_Image'

到目前为止,我发现并一直在处理这个问题:

$SourceFolder = "C:\Pictures\People\People"
$TargetFolder = "C:\Pictures\"
   # Find all files matching *.JPG in the folder specified
Get-ChildItem -Path $SourceFolder -Filter *.jpg |
    ForEach-Object {
        $ChildPath = Join-Path -Path $_.Name.Replace('.jpg','') -ChildPath $_.Name
        [System.IO.FileInfo]$Destination = Join-Path -Path $TargetFolder -ChildPath $ChildPath
   # Create the directory if it doesn't already exits
        if( -not ( Test-Path -Path $Destination.Directory.FullName ) ){
            New-Item -ItemType Directory -Path $Destination.Directory.FullName
            }
        Copy-Item -Path $_.FullName -Destination $Destination.FullName
        }

【问题讨论】:

  • 你的问题是什么?代码乍一看还不错,当然你可以用另一种方式解决问题
  • 问题是它只创建一个文件夹而不是两个。因为我需要它创建的原始文件夹中的子文件夹。

标签: powershell


【解决方案1】:

你让自己变得比需要的更难。

对您的代码的一些增强:

  • 将开关 -File 添加到 Get-ChildItem cmd,这样您就不会同时获得 DirectoryInfo 对象
  • 要获取不带扩展名的文件名,有一个属性.BaseName
  • Join-Path 返回一个字符串,无需将其转换为 [System.IO.FileInfo] 对象
  • 如果将 -Force 添加到 New-Item cmd,则无需检查文件夹是否已存在,因为这将使 cmdlet 要么创建一个新文件夹,要么返回现有的 DirectoryInfo 对象。
    因为我们不需要该对象(以及它的控制台输出),我们可以使用 $null = New-Item ... 将其丢弃

把它们放在一起:

$SourceFolder = "C:\Pictures\People\People"
$TargetFolder = "C:\Pictures"

# Find all files matching *.JPG in the folder specified
Get-ChildItem -Path $SourceFolder -Filter '*.jpg' -File |
    ForEach-Object {
        # Join-Path simply returns a string containing the combined path
        # The BaseName property is the filename without extension
        $ChildPath   = Join-Path -Path $_.BaseName -ChildPath $_.BaseName
        $Destination = Join-Path -Path $TargetFolder -ChildPath $ChildPath
        # Create the directory if it doesn't already exits
        # Using -Force will not give an error if the folder already exists
        $null = New-Item -Path $Destination -ItemType Directory -Force
        $_ | Copy-Item -Destination $Destination
    }

【讨论】:

  • 非常感谢!
最近更新 更多