PowerShell: read lines from text file, construct source and destination file names, then copy files

powershell

I'm a PowerShell novice, and I'd love to be able to script this. I have a text file where each line is part of a file name without the path or extension. I'd like a one-liner that loops through each line of the file (with a gc – Get-Content, right?), takes the content of the line, constructs the source path (the network drive and extension are static), constructs a destination path, and then copies each file. My file content is like this:

12345678
98765432
32145698
12365782

And my source folder is a UNC path like this:

\\server\share

And my destination folder is:

c:\temp\files

I would like to do the equivalent of this DOS command, using $_ as the text from each line of the file:

copy \\server\share\$_.ext c:\temp\files\$_.ext

I'm pretty sure I can use gc and $_ to access each line of the file, and that I need to use cp to copy the files, but I'm having trouble constructing the source and destination file names.

Best Answer

Try the following

gc theFileName | 
  %{ "{0}.ext" -f $_ } |
  %{ copy "\\server\share\$_" "c:\temp\files\$_" }

It can actually be done on one line but it looks better formmated as multiple lines for this answer :)

Related Topic