I'm trying to match filenames using the -like operator, and then copy the files that match with Copy-Item to a new directory:
Declare a list of files:
$files = "File1", "File2", "File3"
$sourceFolder = Get-ChildItem 'C:\source'
Match files by Name Property:
$filesToCopy = @()
foreach ($file in $files) {
$filesToCopy += $sourceFolder | Where-Object {$_.Name -like "$file*"} | Select FullName
}
Finally copy files to destination:
foreach ($file in $filesToCopy) {
Copy-Item $file -Destination 'C:\destination'
}
The last section is returning the error: Copy-Item : Cannot find drive. A drive with the name '@{FullName=C' does not exist.
Output of $filesToCopy:
FullName
--------
C:\source\file1.txt
C:\source\file2.txt
C:\source\file3.txt
What am I doing wrong? FullName seems to be causing an issue.
$filesToCopy (and therefore $file) is an object with a property of FullName, so you need to reference the property to use it correctly:
foreach ($file in $filesToCopy) {
Copy-Item $file.FullName -Destination 'C:\destination'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With