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



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

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

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

这是我正在运行的命令:

gc myfile.txt |% {$_.split(";") | copy $_ "C:mydesireddirectory"}

但我在列表中的每一项都会遇到这样的错误。。。

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:mydesireddirectory"}
    + CategoryInfo          : InvalidArgument: (fileA.txt:String) [Copy-Item], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.CopyItemCommand

不要急于做一句俏皮话,尤其是在刚开始的时候。也就是说,问题是您需要将拆分的内容通过管道传输到另一个ForEach-Object

试试这个:

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

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

Get-Content d:testfile.txt |
  Foreach-Object {$_ -split ';'} |
  Copy-Item -dest d:testxx

还要注意,您使用文件的相对路径,这可能会让您感到痛苦。

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

这里有一个较短的方法(为了好玩):

(${c:tempmyfile.txt }).split(';') | % {cp $_ C:mydesireddirectory}
(Get-Content myfile.txt) -Split ';' | Copy-Item -Destination C:mydesireddirectory

最新更新