Powershell File Length Exception Issue

372 views Asked by At

I have been trying to run this script that captures all the files / folders within a share directory and passes it back to splunk. However the script is giving PathTooLongException 's even though the longest path i can find comes in at 197 characters.

I have tried mapping a share as a folder called z on the root of the C drive which doesnt help at all. Can someone shed some light on how to get around this or what is causing the errors?

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
1

There are 1 answers

2
henrycarteruk On

If you're using a modern version of Powershell (v5.1+ I think) you can get to the paths longer than 260 characters using the unicode version of Windows API.

To do this you prefix the path with \\?\ eg:

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

Note: LiteralPath instead of Path


If you want to use a UNC path (\\server\C$\folder) the syntax is slightly different:

Get-ChildItem -LiteralPath '\\?\UNC\server\C$\folder' -Recurse