使用foreach需要有关简单powershell命令复制的帮助

时间:2011-06-22 00:29:23

标签: powershell copy invalid-argument

我是PowerShell的新手,这个问题将证明这一点。我正在从命令行尝试一个简单的任务,我有一个包含由分号分隔的文件名的txt文件,如...

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

我正在尝试运行一个解析此文件的命令,用分号拆分内容,然后为每个文件运行一个复制命令到所需的目录。

这是我正在运行的命令:

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

但是我为列表中的每个项目收到了这样的错误...

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 个答案:

答案 0 :(得分:8)

抵制制作单行的冲动,特别是在你开始时。也就是说,问题是您需要将拆分内容传递给另一个ForEach-Object

试试这个:

$File = Get-Content .\MyFile.txt
$File | ForEach-Object {
    $_.Split(';') | ForEach-Object {
        Copy-Item -Path "$_" -Destination 'C:\destination'
    }
}

答案 1 :(得分:2)

请注意:您不需要为每个人(@Bacon)嵌套或使用括号(@JPBlanc),只需使用

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

另请注意,您使用文件的相对路径,这可能会让您感到厌烦。

答案 2 :(得分:1)

@Bacon的建议非常好,如果你开始需要发现Powershell CmdLets输出一个对象或一个对象列表,你可以在这些对象上使用属性和方法。

这是一种较短的方式(为了好玩):

(${c:\temp\myfile.txt }).split(';') | % {cp $_ C:\my\desired\directory}

答案 3 :(得分:0)

(Get-Content myfile.txt) -Split ';' | Copy-Item -Destination C:\my\desired\directory