powershell - Powershell文件长度异常问题

标签 powershell pathtoolongexception

我一直在尝试运行此脚本,以捕获共享目录中的所有文件/文件夹,并将其传递回splunk。但是,即使我可以找到的最长路径是197个字符,该脚本也会给出PathTooLongException。

我尝试将共享映射为C驱动器根目录上名为z的文件夹,这根本没有帮助。有人可以阐明如何解决这个问题或导致错误的原因吗?

param (
[string]$directory = "C:\Windows\Logs"
 )
 $errorCount = 0
$OutputList = @()
$directoryLink = 'c:\z'

#set up symbolic link
cmd /c mklink /d $directoryLink $directory

 try
{
$colItems = (Get-ChildItem -Path $directoryLink -Recurse | Sort-Object) 
}
catch
{
$errorCount += 1   
}
foreach ($i in $colItems) 
{
try
{        
    $subFolderItems = (Get-Item $i.FullName | Measure-Object -property 
    length -sum -ErrorAction SilentlyContinue) 
    $acl=$i.GetAccessControl()
    $SizeValue= [Math]::Round(($subFolderItems.sum / 1MB),3)

    $SplunkFileList = New-Object PSObject  
    $SplunkFileList | Add-Member -type NoteProperty -name Filename -Value $i.FullName
    $SplunkFileList | Add-Member -type NoteProperty -name SizeMb -Value $SizeValue
    $SplunkFileList | Add-Member -type NoteProperty -name LastAccess -Value $i.LastAccessTime
    $SplunkFileList | Add-Member -type NoteProperty -name Owner -Value $acl.Owner

    if ($i.PSIsContainer)
    {
        $SplunkFileList | Add-Member -type NoteProperty -name Type -Value "D"
    }
    else
    {
        $SplunkFileList | Add-Member -type NoteProperty -name Type -Value "F"
    }

    $OutputList += $SplunkFileList  

} 
catch [System.IO.IOExeception]
{
    Write-Host 'An Exception was caught.'
    Write-Host "Exception : $($_.Exception.GetType().FullName)"
    $errorCount += 1
    }   
} 
$OutputList | Select-Object Filename,SizeMb,LastAccess,Owner,Type | Format-
List

最佳答案

如果您使用的是现代版本的Powershell(我认为是v5.1 +),则可以使用Windows API的unicode版本获得超过260个字符的路径。

为此,请在路径前面加上\\?\,例如:

Get-ChildItem -LiteralPath '\\?\C:\Windows\Logs' -Recurse

注意:用LiteralPath代替Path
如果要使用UNC路径(\\server\C$\folder),则语法略有不同:
Get-ChildItem -LiteralPath '\\?\UNC\server\C$\folder' -Recurse 

关于powershell - Powershell文件长度异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52420835/

相关文章:

Powershell 错误提示库不可用稍后再试

windows - 如何将 IIS AppPools 的应用程序放入数组?

powershell - 无法在 Exchange 管理控制台中将变量与 Get-User -Filter 一起使用

powershell - 如何将 switch 参数传递给另一个 PowerShell 脚本?

powershell - 使用连续数字后缀在 PowerShell 中批量重命名文件

c# - 如何克服 PathTooLongException?

c# - Directory.SetCurrentDirectory 抛出 PathTooLongException

node.js - Azure Webjob System.IO.PathTooLongException

c# - 从 PathTooLongException 中检索路径信息

azure - VSTS在线新建系统错误 "The specified path, file name, or both are too long."