首页 > 解决方案 > PowerShell 脚本通过创建两个同名的子文件夹将 jpg 文件从一个文件夹复制到另一个文件夹

问题描述

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

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

所以我需要移动C:\Pictures\People\People我将调用 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

解决方案


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

对您的代码的一些增强:

  • 将开关添加-FileGet-ChildItemcmd,这样您就不会获得 DirectoryInfo 对象
  • 要获取没有扩展名的文件名,有一个属性.BaseName
  • Join-Path返回一个字符串,无需将其转换为[System.IO.FileInfo]对象
  • 如果添加-ForceNew-Itemcmd,则无需检查文件夹是否已存在,因为这将使 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
    }

推荐阅读