Copy-Item在PowerShell中的应用;给定路径格式不受支持。

3

我是 PowerShell 的新手,我试图使用一个格式如下的文本文件来复制文件:

file1.pdf
dir1\dir2\dir3\dir 4

file2.pdf
dir1\dir5\dir7\di r8

file3.pdf
...etc.

每个条目的第一行是文件名,第二行是从C:\Users开始的文件路径。例如,文件中第一个条目的完整路径将是:

C:\Users\dir1\dir2\dir3\dir 4\file1.pdf

下面的代码是我目前所拥有的,但是我遇到了一个错误:'给定路径的格式不受支持。',接着又出现了另一个错误告诉我它找不到路径,我认为这是第一个错误的结果。我已经尝试过一些方法来解决,但是我得到的印象是这与将字符串传递给Copy-Item有关。
    $file = Get-Content C:\Users\AJ\Desktop\gdocs.txt
    for ($i = 0; $i -le $file.length - 1; $i+=3)
    {
        $copyCommand = "C:\Users\" + $file[$i+1] + "\" + $file[$i] 
        $copyCommand = $copyCommand +  " C:\Users\AJ\Desktop\gdocs\"
        $copyCommand
        Copy-Item $copyCommand

    }
2个回答

4

您可以分块读取文件的三行,将前两个元素连接起来形成路径,并使用copy-item复制文件。

$to = "C:\Users\AJ\Desktop\gdocs\"

Get-Content C:\Users\AJ\Desktop\gdocs.txt -ReadCount 3 | foreach-object{
    $from = "C:\Users\" + (join-path $_[1] $_[0] )
    Copy-Item -Path $from -Destination $to
}

1

在循环内尝试这个:

$from = "C:\Users\" + $file[$i+1] + "\" + $file[$i] 
$to = "C:\Users\AJ\Desktop\gdocs\"
Copy-Item $from $to

$from$toCopy-Item 命令的参数。它们绑定到 -Path-Destination 参数。您可以通过以下代码进行检查:

Trace-Command -pshost -name parameterbinding { 
   Copy-Item $from $to
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接