Home > Mobile >  Powershell - How to add File Size to an existing Query
Powershell - How to add File Size to an existing Query

Time:01-26

A user provided me with this query;

Get-ChildItem -Filter '*.*'  -recurse -File | 
Select-Object FullName, LastWriteTime |
Sort-Object LastWriteTime -Descending |
Export-Csv '!2023.01.24.AllFiles.csv' -NoTypeInformation -UseCulture

How can I add the file size to the last column? I still need to sort by the LastWriteTime.

FYI: Powershell Noob here...

Looking around it seems that Length is my answer but I keep breaking the applet... :-/

Tried variations of this:

Select-Object -property Length

Select-Object Length

Originally I was hoping to add switches to this command

(gci -filter *.* -recurse).FullName > !!2023.01.24.AllFiles.txt

CodePudding user response:

Following the documentation example, to get the size in KB:

> $size = @{label="Size(KB)";expression={$_.length/1KB}}
> Get-ChildItem -Filter '*.*'  -recurse -File | 
Select-Object FullName, LastWriteTime, $size |
Sort-Object LastWriteTime -Descending |
Export-Csv '!2023.01.24.AllFiles.csv' -NoTypeInformation -UseCulture

CodePudding user response:

You're correct that you can get the file size by pulling the length property; e.g.

Get-ChildItem -Filter '*.*'  -recurse -File | 
Select-Object FullName, LastWriteTime, Length |
Sort-Object LastWriteTime -Descending |
Export-Csv '!2023.01.24.AllFiles.csv' -NoTypeInformation -UseCulture

The Sort-Object doesn't change the content of the records, just their order; so that won't be affected by, and won't affect, the inclusion of the Length property.

If you want the length in KB, MB or GB you can have PowerShell convert it for you; e.g.

Get-ChildItem -Filter '*.*'  -recurse -File | 
Select-Object FullName, LastWriteTime, @{Name='FileSizeInKb';Expression={$_.Length/1KB}} |
Sort-Object LastWriteTime -Descending |
Export-Csv '!2023.01.24.AllFiles.csv' -NoTypeInformation -UseCulture

Per question in comments, to round the number and include KB in the resulting value:

Get-ChildItem -Filter '*.*'  -recurse -File | 
Select-Object FullName, LastWriteTime, @{Name='FileSizeInKb';Expression={"$([int]($_.Length/1KB)) KB"}} |
Sort-Object LastWriteTime -Descending |
Export-Csv '!2023.01.24.AllFiles.csv' -NoTypeInformation -UseCulture
  • Related