then the result is “Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData”.
Which is not exactly whatI want
I’d recommend creating a PSCustomObject instead of formatting the data. It’s a lot more flexible. Or better yet, build out your script as a function without limiting the data being passed and use Select-Object in the pipe naturally. But if you’re looking for a report kind of script, then PSCustomObject is probably a better way to go.
Format-Table turns the file system objects into a formatting object, which if you try to use Write-Host on converts to a very unhelpful string. If you replace Format-Table with Select-Object and then just let it fall out off the pipeline without catching it in a variable, you should get what you want. I also powershellerized the loop.
Your logic is a bit messed up. In your post you don’t show what you are running the Format-Table against, but you are overwriting it each time. There are two methods of creating an object with all results, I like assigning the results to the for loop and the other appends data as it goes (currently remarked out):
$rootdir = "C:\Windows"
$directories = @("\Diagnostics",
"\Debug",
"\Fonts")
$results = foreach ($directory in $directories) {
Get-ChildItem -path ("{0}{1}" -f $rootdir, $directory) | Sort-Object CreationTime -Descending | Select -First 1
}
#$results = @() #Create a blank object (array) to add items to
#foreach ($directory in $directories) {
#Add each result to the blank object (array)
# $results += Get-ChildItem -path ("{0}{1}" -f $rootdir, $directory) | Sort-Object CreationTime -Descending | Select -First 1
#}
$results | Format-Table -Property CreationTime, LastWriteTime, FullName, Length