【问题标题】:Copy-Item in PowerShell; The given path's format is not supportedPowerShell 中的复制项;不支持给定路径的格式
【发布时间】:2011-09-14 17:34:29
【问题描述】:

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

    }

【问题讨论】:

    标签: windows string powershell


    【解决方案1】:

    您可以分三行读取文件,将前两个元素连接起来形成路径,然后使用 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
    }
    

    【讨论】:

      【解决方案2】:

      试试这个(在循环内):

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

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

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

      【讨论】:

        猜你喜欢
        • 2011-11-13
        • 2012-04-21
        • 1970-01-01
        • 1970-01-01
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 2017-09-14
        相关资源
        最近更新 更多