PowerShell basics: using Get-Content to drive a copy

I recently saw a forum question about copying files where the file names where in a file

Icreated a file with the full path to the files that need to be copied

Get-ChildItem -path c:\test -Filter proc* | foreach {Add-Content -Value $_.Fullname -Path c:\test\files2copy.txt}

the content of the file can be seen

PS> Get-Content -Path c:\test\files2copy.txt
C:\test\proc1.txt
C:\test\proc2.txt

to copy the files to another folder

Get-Content -Path c:\test\files2copy.txt | foreach {Copy-Item -Path $_ -Destination c:\Teszzt2}

 

The trick with get-content is that it creates an array of strings – one per line of the file

Alternatively we could do this

$files = Get-Content -Path c:\test\files2copy.txt
foreach ($file in $files){Copy-Item -Path $file -Destination c:\Teszzt2}

 

the second option my be better if you need to perform further processing on the files

Published Fri, Jun 24 2011 20:12 by RichardSiddaway

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: