Hello Guys,
I’m new in forum and also new in powershell community. I got a task to write a script which copies file to folders, which matches expression in name. For example, I got these filenames:
file1: C:\Documents\M_20190103_0609_GDA48H2 _YS2R4X20002122620.ddd
file2: C:\Documents\M_20190812_1459_WGM 68110_XLRTEH4300G277302.ddd
file3:C:\Documents\M_20191216_1705_WGM_14315_XLRTEH4300G155004.ddd
These files must be copied to these folders:
C:\Documents\M_20191216_1705_WGM_14315_XLRTEH4300G155004 -> D:\Cars\WGM14315
C:\Documents\M_20190812_1459_WGM 68110_XLRTEH4300G277302.ddd -> D:\Cars\WGM68110
C:\Documents\M_20191216_1705_WGM_14315_XLRTEH4300G155004.ddd ->D:\Cars\WGM14315
I wrote some code but it does not work that i won’t. It creates the directory that matches regex, but dont copy to folder. Here is my code:
$documents = "C:\Documents"
$dest_dir = "D:\Cars"
$filetype = "*.ddd"
$files = Get-ChildItem -path $documents -filter $filetype
$regex = [regex]"([A-Z]{2,3}[_]{0,2}[ ]{0,2}[0-9A-Z]{4,5})"
foreach($file in $documents){
if($file -match $new_reg){
$new_path = Join-Path -Path $dest_dir -ChildPath $Matches[0]
if(!(Test-path -Path $new_path -PathType Container)){
New-Item -ItemType Directory -path $new_path
}else {
Write-Host "$($matches[0]) exists."
}
$file | Copy-Item -Destination (Join-Path $tacho_dirs -childpath $Matches[0] )
}
}
These code creates a directory matches regex and copies files matches regex, but it doesn’t copy to destination folders. Is this possible to copy files to destination directories without creating unnecessary directories? Maybe hash table will be useful? I tried:
$rej_names= $files.Name.Substring(16,10) -replace 'Y','' -replace 'S','' -replace '_','' -replace ' ',''
$hash_map = @{}
for($i =0; $i -lt $files.Count; $i++){
$hash_map[$files.FullName[$i]]= ((Join-path -path $dest_dir -childpath $rej_names[$i]))
}
The hash map is correct, but it doesn’t copy files from hash key to directories that are hash values.
Any suggestion?I will be very grateful for your help in solving the problem.