Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a list of files from array

Tags:

powershell

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.

like image 581
LightningWar Avatar asked Dec 20 '25 07:12

LightningWar


1 Answers

$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'
}
like image 56
Gareth Lyons Avatar answered Dec 21 '25 23:12

Gareth Lyons