PowerShell Get-ChildItem - Path Too Long

6,273

There are 2 other solutions for this

As of Windows 10 / Windows server 2016 (Build 1607 or newer) you can use to remove

Set-ItemProperty 'HKLM:\System\CurrentControlSet\Control\FileSystem' -Name LongPathsEnabled' -value 1

If you are using PowerShell 5.1 or above you can use

get-childitem -LiteralPath

So in this case you would define $Source = "\\?\C:\Users\User1" and replace Get-ChildItem -Path "$Source\*.*" -Recurse -Force with Get-ChildItem -LiteralPath "$Source\*.*" -Recurse -Force

Share:
6,273

Related videos on Youtube

ZazzyTech
Author by

ZazzyTech

Updated on September 18, 2022

Comments

  • ZazzyTech
    ZazzyTech over 1 year

    I have been stuck with trying to format my output table for a Get-ChildItem command.

    I have created a script to scan a directory defined in $Source to search for files defined by $Months and $Size. This works fine but some of the directories are longer than 248 characters long and I get file path too long error.

    So I want to not include the $Source path when it is output to the directory column in the table.

    For example I want to see this:

    | file1.csv | Last Write Access | .\Desktop\Folder1 |  
    | file2.txt | Last Write Access | .\Desktop\Folder2 |
    

    when the $Source is defined as C:\users\User1

    Here is my current code:

    $Source = "C:\Users\User1"
    $Months = "24"
    $Size = 10MB
    $OutSource = "C:\Export"
    $LogName = "Export"
    $Ext = "csv"
    
    $Date = (Get-Date).AddMonths(-$Months)
    
    Get-ChildItem -Path "$Source\*.*" -Recurse -Force | `
        Where-Object {$_.LastAccessTime -lt $Date -and $_.Length -gt $Size} | `
            Format-Table -AutoSize -Property Name, LastWriteTime, LastAccessTime, Directory | `
                Out-String -Width 4096 | `
                    Out-File $OutSource\$LogName.$Ext
    
  • Matthew Wetmore
    Matthew Wetmore about 6 years
    New-PSDrive is the PowerShell way to do it - but net use will also do the trick.