问题描述
|
我是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
}
解决方法
您可以分三行阅读文件,将前两个元素结合起来形成路径,然后使用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
}
, 试试这个(在周期内):
$from = \"C:\\Users\\\" + $file[$i+1] + \"\\\" + $file[$i]
$to = \"C:\\Users\\AJ\\Desktop\\gdocs\\\"
Copy-Item $from $to
$from
和$to
是Copy-Item
cmdlet的参数。它们绑定到参数-Path和-Destinattion。您可以通过以下代码进行检查:
Trace-Command -pshost -name parameterbinding {
Copy-Item $from $to
}