4

I'm new to powershell and this question will prove that point. I'm trying a simple task from the command line where I have a txt file containing filenames separated by semicolons like...

fnameA.ext;fnameB.ext;fnameC.ext;....

I'm trying to run a command which will parse this file, split the contents by semicolon, and then run a copy command for each file to a desired directory.

Here is the command I'm running:

gc myfile.txt |% {$_.split(";") | copy $_ "C:\my\desired\directory"}

But I'm getting an error like this for each item in the list...

Copy-Item : The input object cannot be bound to any parameters for the command either because the command does not take
 pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:36
+ gc bla.txt |% {$_.split(";") | copy <<<<  $_ "C:\my\desired\directory"}
    + CategoryInfo          : InvalidArgument: (fileA.txt:String) [Copy-Item], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.CopyItemCommand
Dave
  • 6,141
  • 2
  • 38
  • 65

4 Answers4

10

Resist the urge to make one-liners, especially when you're starting out. That said, the problem is you need to pipe the split content to another ForEach-Object.

Try this:

$File = Get-Content .\MyFile.txt
$File | ForEach-Object {
    $_.Split(';') | ForEach-Object {
        Copy-Item -Path "$_" -Destination 'C:\destination'
    }
}
Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
2

Just a note: you don't need to nest for-eachs (@Bacon) or use parenthesis (@JPBlanc), just use

Get-Content d:\test\file.txt |
  Foreach-Object {$_ -split ';'} |
  Copy-Item -dest d:\test\xx

Also note that you use relative paths to files, which might bite you.

stej
  • 28,745
  • 11
  • 71
  • 104
1

The advice of @Bacon is very good if you begin you need to discover that Powershell CmdLets output an object or a list of objects and that you can use properties and methods on these objects.

Here is a shorter way (for the fun) :

(${c:\temp\myfile.txt }).split(';') | % {cp $_ C:\my\desired\directory}
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • I tried this and this is originally the kind of solution I was hoping for; but I had to mess with it a little bit to get it to work. Here is what I ended up using `(gc myfile.txt).split(';') | % {cp $_ "C:\my\desired\directory"}` – Dave Jun 22 '11 at 14:48
  • I was getting `You cannot call a method on a null-valued expression. At line:1 char:20 + (${myfile.txt}).split <<<< (';') | % {cp $_ C:\my\desired\directory`} – Dave Jun 22 '11 at 14:50
  • I Edited : in fact you must code the full path of the file when you are using ${} form. – JPBlanc Jun 22 '11 at 15:04
0
(Get-Content myfile.txt) -Split ';' | Copy-Item -Destination C:\my\desired\directory
Shay Levy
  • 121,444
  • 32
  • 184
  • 206