Powershell 使用长文件路径时获取ChildItem错误处理

Powershell 使用长文件路径时获取ChildItem错误处理,powershell,Powershell,我试图处理扫描文件夹时出现的错误。比如说,我有一些类似于: Get-ChildItem $somepath -Directory | ForEach-Object { if(error occurred due to too long path) { skip this folder then } else { Write-Host $_.BaseName } } 执行此操作时,我会在$somepath中打印文件夹,直到其中一个太长,然后循环停止

我试图处理扫描文件夹时出现的错误。比如说,我有一些类似于:

Get-ChildItem $somepath -Directory | ForEach-Object {
   if(error occurred due to too long path) {
        skip this folder then
   } else {
       Write-Host $_.BaseName
   }
}

执行此操作时,我会在
$somepath
中打印文件夹,直到其中一个太长,然后循环停止。即使使用
SilentlyContinue
。即使到达太长的文件夹后,我也要打印。

您可以尝试使用
Where Object
cmdlet忽略长度超过260个字符的文件

Get-ChildItem $somepath -Directory -ErrorAction SilentlyContinue `
    | Where-Object {$_.length -lt 261} `
    | ForEach-Object { Write-Host $_.BaseName }
或者您可以使用以下命令()


如果您可以安装非早期的PowerShell版本(3.0或更新版本),只需在路径前面加上
\\?\
,即可克服完整路径的260个字符限制:

Get-ChildItem "\\?\$somepath" | ForEach {
    # ............
}

我将添加我的解决方案,因为此页面上的两个都不适用于我。我使用的是相对路径,因此无法使用
\\
前缀

$TestFiles = Get-ChildItem $pwd "*Tests.dll" -Recurse | Where-Object {$_.FullName.length -lt 261} | Select-Object FullName -ExpandProperty FullName | Where-Object FullName -like "*bin\Release*"
Write-Host "Found TestFiles:"
foreach ($TestFile in $TestFiles) {
    Write-Host "   $TestFile"
}

我甚至在使用SilentlyContinue时也写过:(然后它不会打印错误,但不会打印超过该点。这对我来说不起作用。我喜欢长度的想法,但我们不想使用
$\uu.FullName.length
?不要通过双重发布再次询问您的问题。您可以处理异常:[System.IO.PathTooLongException]我必须找到一个引用,但我的印象是这已经不起作用了。可能是因为我不知道,但运行此命令时会出错:
路径中的非法字符。
无法检索cmdlet的动态参数。
…PS5.1+Win7:是的,它在PS2中不起作用,因为我刚刚尝试运行了
powershell-version 2
这一部分很有意义。我在10上运行v5。谢谢你的图片。如果有人对这方面的文档感兴趣:
$TestFiles = Get-ChildItem $pwd "*Tests.dll" -Recurse | Where-Object {$_.FullName.length -lt 261} | Select-Object FullName -ExpandProperty FullName | Where-Object FullName -like "*bin\Release*"
Write-Host "Found TestFiles:"
foreach ($TestFile in $TestFiles) {
    Write-Host "   $TestFile"
}