Copy directories when their name matches -Like txt files
-
26-12-2019 - |
Question
I am trying to copy a bunch of directories. I have text files which have a similar name and I need to match the directories to those text files to determine which directories to copy.
This is what I have done and I can't figure out how to fix it. I am going around in circles.
$destination = "..\..\$args\Images\"
$txtfiles = Get-ChildItem $destination -Include *.txt
$source = "..\..\..\Images\" | ?{ $_.PSIsContainer } | Where-Object { $_.Name -Like "*$txtfiles*" } | Copy-Item $destination
An example of a txt file: 1e03655b-0aac-48b2-82f3-75942084af7a.txt
and folder: name.1e03655b-0aac-48b2-82f3-75942084af7a
So I need to find the folders that match the txt files and copy the folder to the txt file directory.
Thanks
Solution
You want to expand the BaseName properties of those text files (to cut off the .txt part) and have an array of strings such as:
1e03655b-0aac-48b2-82f3-75942084af7a
1e03655b-0aac-48b2-82f3-75942084af7b
1e03655b-0aac-48b2-82f3-75942084af8g
1e03655b-0aac-48b2-82f3-75942084afba
Then your $source =
line needs to pull a directory listing and not just pipe a string down the pipeline, and then I would suggest matching the directory names with a regex match, and checking to see if that match is -in $txtfiles
.
$destination = "..\..\$args\Images\"
$txtfiles = Get-ChildItem $destination -Filter *.txt | Select -ExpandProperty BaseName
$source = "..\..\..\Images\"
GCI $source -Directory | ?{ $_.Name -match "(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$" } | %{If($Matches[1] -in $txtfiles){Copy-Item $_.FullName $destination}}