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
Best Answer
There are 2 other solutions for this
As of Windows 10 / Windows server 2016 (Build 1607 or newer) you can use to remove
If you are using
PowerShell 5.1
or above you can useSo in this case you would define
$Source = "\\?\C:\Users\User1"
and replaceGet-ChildItem -Path "$Source\*.*" -Recurse -Force
withGet-ChildItem -LiteralPath "$Source\*.*" -Recurse -Force