4

我是 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

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-eachs (@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 回答