我正在尝试根据文件名将文件复制到特定的文件夹。
例如:
当前文件夹- C:\Stuff\Old Files\
文件-206.小Rock.map.pdf
目标文件夹- D:\Cleanup\206\Repository
因此,文件(206)上的前导数字基本上是子文件夹的一部分。"\Repository“将保持不变。只有前导数字才会改变。
如果文件是207。小Rock.map.pdf,那么目标文件夹将是
D:\Cleanup\207\Repository
我从这里得到的代码开始,但我不确定如何解释数字的变化,以及如何让它在文件夹不存在的情况下创建文件夹。因此,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;
发布于 2018-06-03 09:47:44
这里有一些你可以尝试的东西。目录的号码是从正则表达式匹配"(\d+)\..*.pdf"
中获取的。当您确信将创建正确的文件副本时,请从Copy-Item
cmdlet中删除-WhatIf
。
我没有尝试解决Write-Progress
功能。此外,这将仅复制以数字开头后跟句号(句点)字符的.pdf文件。
我不完全理解所有Write-Host
和Read-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;
https://stackoverflow.com/questions/50662140
复制相似问题