Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 基于文件名将文件复制到指定的文件夹。如果没有创建文件夹';不存在_Powershell_Directory_Powershell 2.0_File Copying_Movefile - Fatal编程技术网

Powershell 基于文件名将文件复制到指定的文件夹。如果没有创建文件夹';不存在

Powershell 基于文件名将文件复制到指定的文件夹。如果没有创建文件夹';不存在,powershell,directory,powershell-2.0,file-copying,movefile,Powershell,Directory,Powershell 2.0,File Copying,Movefile,我正在尝试根据文件名将文件复制到特定文件夹 例如: 当前文件夹-C:\Stuff\Old Files\ 文件-206.littlerock.map.pdf 目标文件夹-D:\Cleanup\206\Repository 因此,文件(206)上的前导号基本上是子文件夹的一部分。“\Repository”将保持不变。只有前导号码会改变 如果文件是207.Little Rock.map.pdf,那么目标文件夹将是 D:\Cleanup\207\Repository 我从这里得到的代码开始,但我不确定如

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

例如:

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

文件-206.littlerock.map.pdf

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

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

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

D:\Cleanup\207\Repository

我从这里得到的代码开始,但我不确定如何解释数字的变化,以及如果文件夹不存在,如何让它创建一个文件夹。所以206\存储库可能已经存在,但如果它不存在,我需要脚本来创建文件夹

$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;

这里有一些你可以试试的东西。目录的编号取自正则表达式匹配项,
“(\d+)\..*.pdf”
。当您确信将生成正确的文件副本时,请从
复制项
cmdlet中删除
-WhatIf

我没有尝试解决
编写进度
功能。此外,这将仅复制以数字开头,后跟句号(句点)字符的.pdf文件

我不完全理解所有
写主机
读主机
用法的必要性。这不是很可怕。普华永道

$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;
这应该是你需要的。您可能需要稍微调整目标路径,但这应该是非常直接的。我强烈建议使用“-”作为文件前缀的分隔符,而不是“.”,因为这样可以防止在错误的位置执行目录中的每个文件时意外移动

另外,在编写脚本时,请创建函数来执行各个工作单元,然后在最后调用这些函数。这样修改和调试就容易多了

<#
.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

[CmdletBinding()]
param(
[字符串]$SourceIn,
[字符串]$DestinationIn
)
函数集目标路径{
param(
[字符串]$FileName,
[字符串]$Target
)
[string]$NewParentFolderName=$FileName.SubString(0,$FileName.IndexOf('-'))
[string]$DestinationPath=Join Path-Path$Target-ChildPath$NewParentFolderName
返回$DestinationPath
}  
函数Create DestinationPath{
[CmdletBinding()]
param(
[字符串]$Target
)
if(-not(测试路径-路径$Target)){
试一试{
新建项-项类型目录-路径$Target |写入详细信息
}
抓住{
写入错误$Error[0];
}
}
否则{
写入详细信息“$Target exists”
}
}
函数Move MyFiles{
[CmdletBinding()]
param(
[字符串]$Source,
[字符串]$Destination
)
[array]$FileList=Get ChildItem$Source-File |选择对象-ExpandProperty'Name'
foreach($FileList中的文件){
[字符串]$DestinationPath=设置DestinationPath-文件名$file-目标$Destination
创建DestinationPath-目标$DestinationPath
试一试{
移动项目-路径(连接路径-路径$Source-ChildPath$文件)-目标$DestinationPath |写入详细信息
}
抓住{
写入警告$Error[0]
}
}
}
移动MyFiles-源$SourceIn-目标$DestinationIn

谢谢!这让我非常接近。我要再调整一下。