Working on a script to copy files to specific existing folders based on a substring of the file name.
The files are named in a format that ends with year and month numbers, such as:
RawData_MJE_2019_7.xlsx Checklist_2019_7.xlsx RawData_MJE_2019_6.xlsx Checklist_2019_6.xlsx
I have existing destination directories named with the year and month in a similar format, such as:
C:\Save\2019_7 C:\Save\2019_8
Looking to have source files containing a year and month in the file name copied to the similarly named destination directory? So any source files containing 2019_7 would be copied to the C:\Save\2019_7 folder.
I'm getting error on the copy-item; wondering if it's due to spaces in the folder names of the destination directory:
$SourceFolder = "C:\Users\hy85170\Documents\VBTemp\Output\Formatted"
$TargetFolder = "C:\Users\hy85170\OneDrive - Chemours\Documents\Chemours\CONTROLLERSHIP\Data Analytics\MJE\0. Data\1. Output Files\To Upload"
$Files = Get-ChildItem $SourceFolder | where {$_.extension -in ".xlsx"} | select -expand basename
Foreach ($File in $Files)
{
$Year = $File.Substring(0,4)
$Month = $File.Substring(4,1)
$Directory = $TargetFolder + "\" + $Year+$Month
$files | Copy-Item -Destination $Directory
}
Error:
Copy-Item : Cannot find path 'C:\Users\hy85170\RawDataWhole_MJE_2019_7' because it does not exist. At C:\Users\hy85170\Desktop\VBTemp\VBScripts\CopyOutputFiles.ps1:11 char:11 + $files | Copy-Item -Destination $Directory + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\Users\hy85170\RawDataWhole_MJE_2019_7:String) [Copy-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
$Files
[the plural] in your copy command. that is NOT the name you used for the current loop item. [grin] ///// you expanded the file basename and then don't add the extension back on before you do the copy. that makes your copy command fail since there are no such files in the source location. – Lee_Dailey