0

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
phuclv
  • 159
  • 16
ZazzyTech
  • 1
  • 1
  • 3

2 Answers2

3

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

Drifter104
  • 3,693
  • 2
  • 22
  • 39
0

After an extensive search and trial and error, I have found a solution to my problem.

As there is no way to truncate the first part of the path, I have instead added a line of code to create a temporary network drive to do the truncating.

Code used:

New-PSDrive "X" -PSProvider FileSystem -Root "$Source"

And changed the

Get-ChildItem -Path "$Source\*.*" -Recurse -Force | `

To

Get-ChildItem -Path "X:\*.*" -Recurse -Force | `

So my current output is somewhat what I was after:

| file1.csv | Last Write Access | X:\Desktop\Folder1 |
| file2.txt | Last Write Access | X:\Desktop\Folder2 |
Worthwelle
  • 109
  • 4
ZazzyTech
  • 1
  • 1
  • 3