根据文件名复制基于指定文件夹的文件。创建文件夹(如果它不存在)

时间:2018-06-02 23:51:20

标签: powershell directory powershell-v2.0 file-copying movefile

我正在尝试根据文件名将文件复制到特定文件夹。

例如:

当前文件夹 - C:\ Stuff \ Old Files \

File-206.Little Rock.map.pdf

目标文件夹 - D:\ Cleanup \ 206 \ Repository

所以基本上文件(206)上的前导号码是子文件夹的一部分。 “\ Repository”将保持不变。只有前导号码才会改变。

如果文件是207.Little Rock.map.pdf,那么目标文件夹将是

d:\清理\ 207 \存储库

我从这里得到的代码开始,但我不知道如何解释数量的变化以及如果文件夹不存在,如何创建文件夹。所以206 \ Repository可能已经存在,但如果不存在,我需要脚本来创建文件夹。

$SourceFolder = "C:\Stuff\Old Files\"
$targetFolder = "D:\Cleanup\"
$numFiles = (Get-ChildItem -Path $SourceFolder -Filter *.pdf).Count
$i=0

clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $SourceFolder ' to ' $targetFolder
Read-host -prompt 'Press enter to start copying the files'

Get-ChildItem -Path $SourceFolder -Filter *.PDF | %{ 
    [System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $Name.Repository(".*","\"))

   if(!(Test-Path -Path $destination.Directory )){
    New-item -Path $destination.Directory.FullName -ItemType Directory 
    }
    [int]$percent = $i / $numFiles * 100

    copy-item -Path $_.FullName -Destination $Destination.FullName
    Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
    $i++
}
Write-Host 'Total number of files read from directory '$SourceFolder ' is ' $numFiles
Write-Host 'Total number of files that was copied to '$targetFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;

2 个答案:

答案 0 :(得分:1)

这应该主要你需要什么。您可能需要稍微调整一下目标路径,但这应该是相当直接的。我强烈建议使用' - '作为文件前缀的分隔符而不是'。'。因为如果您碰巧在错误的地方执行它,这将防止意外移动目录中的每个文件。

此外,当您编写脚本时,请创建函数以执行单个工作单元,然后在最后调用这些函数。修改和调试这种方式要容易得多。

<#
.SYNOPSIS
  Moves files from source to destination based on FileName
  Creates destination folder if it does not exist. 
.DESCIPTION
  The script expects files with a prefix defined by a hyphen '-' i.e. 200-<filename>.<ext>.
  There is no filename validation in this script; it will *probably* skip files without a prefix.
  A folder based on the prefix will be created in the destination. 
  If your file is name string-cheese.txt then it will be moved to $DestinationIn\string\string-cheese.txt
.PARAMETER SourceIn
  Source Path (folder) where your files exist.
.PARAMETER DestinationIn
  Target Path (folder) where you want your files to go.
.EXAMPLE
  & .\CleanUp-Files.ps1 -SourceIn "C:\Users\User\Documents\Files\" -DestinationIn "C:\Users\User\Documents\Backup\" -Verbose
.NOTES
  Author: RepeatDaily
  Email: RepeatedDaily@gmail.com

  This script is provided as is, and will probably work as intended.  Good Luck!
  https://stackoverflow.com/questions/50662140/copy-file-based-a-specified-folder-based-on-file-name-create-folder-if-it-doesn
#>
[CmdletBinding()]
param (
  [string]$SourceIn,
  [string]$DestinationIn
)

function Set-DestinationPath {
  param (
    [string]$FileName,
    [string]$Target
  )
  [string]$NewParentFolderName = $FileName.SubString(0,$FileName.IndexOf('-'))
  [string]$DestinationPath = Join-Path -Path $Target -ChildPath $NewParentFolderName

  return $DestinationPath
}  

function Create-DestinationPath {
  [CmdletBinding()]
  param (
    [string]$Target
  )
  if (-not(Test-Path -Path $Target)) {
    Try {
      New-Item -ItemType Directory -Path $Target | Write-Verbose
    }
    catch {
      Write-Error $Error[0];
    }
  }
  else {
    Write-Verbose "$Target exists"
  }
}

function Move-MyFiles {
  [CmdletBinding()]
  param (
    [string]$Source,
    [string]$Destination
  )
  [array]$FileList = Get-ChildItem $Source -File | Select-Object -ExpandProperty 'Name'

  foreach ($file in $FileList) {
    [string]$DestinationPath = Set-DestinationPath -FileName $file -Target $Destination

    Create-DestinationPath -Target $DestinationPath

    try {
      Move-Item -Path (Join-Path -Path $Source -ChildPath $file) -Destination $DestinationPath | Write-Verbose
    }
    catch {
      Write-Warning $Error[0]
    }
  }
}

Move-MyFiles -Source $SourceIn -Destination $DestinationIn

答案 1 :(得分:0)

您可以尝试以下方法。从正则表达式匹配"(\d+)\..*.pdf"中获取目录的编号。如果您确信将创建正确的文件副本,请从-WhatIf cmdlet中删除Copy-Item

我没有尝试解决Write-Progress功能。此外,这只会复制以数字开头的.pdf文件,后跟一个FULL STOP(句点)字符。

我不完全理解所有Write-HostRead-Host用法的必要性。它不是非常PowerShell。 pwshic

$SourceFolder = 'C:/src/t/copymaps'
$targetFolder = 'C:/src/t/copymaps/base'

$i = 0
$numFiles = (
    Get-ChildItem -File -Path $SourceFolder -Filter "*.pdf" |
        Where-Object -FilterScript { $_.Name -match "(\d+)\..*.pdf" } |
        Measure-Object).Count

clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $SourceFolder ' to ' $targetFolder
Read-host -prompt 'Press enter to start copying the files'

Get-ChildItem -File -Path $SourceFolder -Filter "*.pdf" |
    Where-Object -FilterScript { $_.Name -match "(\d+)\..*.pdf" } |
    ForEach-Object {
        $NumberDir = Join-Path -Path $targetFolder -ChildPath $Matches[1]
        $NumberDir = Join-Path -Path $NumberDir -ChildPath 'Repository'
        if (-not (Test-Path $NumberDir)) {
            New-Item -ItemType Directory -Path $NumberDir
        }

        Copy-Item -Path $_.FullName -Destination $NumberDir -Whatif
        $i++
    }

Write-Host 'Total number of files read from directory '$SourceFolder ' is ' $numFiles
Write-Host 'Total number of files that was copied to '$targetFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;