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
4

4 に答える 4

10

特に始めたばかりのときは、ワンライナーを作りたいという衝動に抵抗してください。とはいえ、問題は、分割されたコンテンツを別の にパイプする必要があることですForEach-Object

これを試して:

$File = Get-Content .\MyFile.txt
$File | ForEach-Object {
    $_.Split(';') | ForEach-Object {
        Copy-Item -Path "$_" -Destination 'C:\destination'
    }
}
于 2011-06-22T00:39:31.103 に答える
2

注意: for-each (@Bacon) をネストしたり、括弧 (@JPBlanc) を使用したりする必要はありません。

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

また、ファイルへの相対パスを使用していることにも注意してください。

于 2011-06-22T05:46:57.610 に答える
1

Powershell CmdLetsがオブジェクトまたはオブジェクトのリストを出力し、これらのオブジェクトでプロパティとメソッドを使用できることを発見する必要がある場合、@Baconのアドバイスは非常に優れています。

ここに短い方法があります(楽しみのために):

(${c:\temp\myfile.txt }).split(';') | % {cp $_ C:\my\desired\directory}
于 2011-06-22T04:10:21.307 に答える
0
(Get-Content myfile.txt) -Split ';' | Copy-Item -Destination C:\my\desired\directory
于 2011-06-22T07:51:51.760 に答える