【问题标题】:PowerShell copy fails without warningPowerShell 复制失败且没有警告
【发布时间】:2011-01-29 18:42:20
【问题描述】:

您好,我正在尝试将文件从 IE 缓存复制到其他地方。这适用于 w7,但不适用于 Vista Ultimate。

简而言之:

复制项目 $f -Destination "$targetDir" -force

(我也试过 $f.fullname)

完整的脚本:

$targetDir = "C:\temp"
$ieCache=(get-itemproperty "hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders").cache

$minSize = 5mb
Write-Host "minSize:" $minSize
Add-Content -Encoding Unicode -Path $targetDir"\log.txt" -Value (get-Date)

Set-Location $ieCache
#\Low\Content.IE5 for protected mode
#\content.ie5 for unprotected

$a = Get-Location 

foreach ($f in 
        (get-childitem -Recurse -Force -Exclude *.dat, *.tmp | where {$_.length -gt $minSize})
        )
        {           
        Write-Host (get-Date)   $f.Name $f.length       
        Add-Content -Encoding Unicode -Path $targetDir"\log.txt" -Value $f.name, $f.length
        copy-item $f -Destination "$targetDir" -force
        }

智慧的终结。请帮忙!

【问题讨论】:

    标签: powershell copy-item


    【解决方案1】:

    如果您在尝试找出参数在 PowerShell 中无法正确绑定的原因时遇到问题,请使用 Trace-Command,如下所示:

    Trace-Command -Name ParameterBinding -expr { copy-item $f foo.cat.bak } -PSHost
    

    在这种情况下,它对我有用。也许这是 PowerShell 2.0 的一个“功能”,但您可以看到它在触发之前尝试绑定几个不同的时间:

    COERCE arg to [System.String]
        Trying to convert argument value from System.Management.Automation.PSObject to System.String
        CONVERT arg type to param type using LanguagePrimitives.ConvertTo
        CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [C:\Users\Keith\foo.cat]
    

    FileInfo 对象通过管道传递时的正常工作方式,它们通过“PropertyName”绑定到 LiteralPath 参数。我知道,您可能想知道,呃,您认为 System.IO.FileInfo 没有 LiteralPath 属性。呵呵,不会的。那些狡猾的 PowerShell 人员将 PSPath 别名偷偷添加到 LiteralPath 参数中,并且 PowerShell “适应”每个 FileInfo 对象以添加许多 PS* 属性,包括 PSPath。因此,如果您想“从字面上”匹配您将使用的流水线行为:

    Copy-Item -LiteralPath $f.PSPath $targetDir -force
    

    请注意,在这种情况下,您不必引用 $targetDir(作为参数参数)。

    【讨论】:

      【解决方案2】:

      copy-item 不起作用的原因是您将System.IO.FileInfo 作为参数-path 传递。 正确的做法有两种可能:

      1. copy-item -literal $f.Fullname -destination ...
      2. $f | copy-item -destination ...

      请注意,我使用参数-literalPath,因为临时文件夹中的文件通常在名称中包含[],它们充当通配符。

      如果您想知道为什么案例 #2 有效,请查看“help Copy-Item -Parameter Path”,您会看到接受管道输入?真(按值,按属性名称)。欲了解更多信息,请查看 Keith 的电子书 Effective Windows PowerShell

      为什么你的版本不起作用?因为参数-path(位于位置 1)接受[string[]] 类型的输入,而不是FileInfo。因此 PowerShell 尝试将其转换为 [string](然后转换为数组),但它可能只使用了 Name 属性。你可以这样试试:

      [string[]] (gci | select -first 1)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-23
        • 1970-01-01
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        相关资源
        最近更新 更多