Your question is similar to this post that was just answered.
Move-item 2 issues - PowerShell Help - PowerShell Forums
The code currently is trying to collect the names of files in a directory, not what was actually deleted in a directory. If you want verbose logging, you need to process the files separately. Get-ChildItem is returning Files and Directories, so the code is deleting all subdirectories too which you are not collecting with Get-ChildItem. Another thing is just logging the name is a bit pointless, you at least want a path and name (e.g FullName), but even more you should be logging with a PSObject, not just text in a log file. Take look at the following (not tested, but should be close):
$dirs = "C:\Scripts\*"
$results = foreach ($dir in $dirs) {
#Get all files in the directory and all sub-directories
$files = Get-ChildItem -Path $dir -File -Recurse
#Process the files one by one and delete them.
foreach ($file in $files) {
try {
Remove-Item -Path $file.FullName -Force -ErrorAction Stop -WhatIf
$Status = 'SUCCESS'
}
catch {
$Status = 'FAILED: {0}' -f $_
}
#Return the file information to the $results variable
$file |
Select-Object Name,
FullName,
Length,
@{Name='Status';Expression={$status}}
}
#Delete folders with no logging
$folders = Get-ChildItem -Path $dir -Directory |
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
}
#Success
$results | Where-Object {$_.Status -eq 'Success'}
#Failed
$results | Where-Object {$_.Status -ne 'Success'}
#Export
#$results | Export-Csv -Path 'C:\mystuff.csv' -NoTypeInformation
It also appears that you are trying to write to the host with output. Rather than outputting a bunch of filenames to the screen, look at Write-Progress that will tell you how far in deleting process has been completed as you’ll just be scrolling with a bunch of names that doesn’t really provide any value and the buffer isn’t big enough to hold all of that data. Using a progress bar will be much more useful to who is monitoring the process.