How Do I Sort and Display a PowerShell Array?

93 Views Asked by At

I'm trying to sort an array of System.IO.FileInfo objects by lastWriteTime, then display each entry’s file name, lastWriteTime & file size on the console.

But before I can output anything, the entire array (1,100+ items) is written to the console in tabular format, and I can’t figure out how to stop it.

Here’s the sort code ($queue is the System.IO.FileInfo array).

$queue | Sort-Object -property lastWriteTime 

I tried piping Sort-Object’s output to out-null, but it had no effect.

Does anyone see what I’m doing wrong, or know where to find a working example? None of the examples I’ve seen online shed any light on the issue.

$PSVersionTable output:

Name                           Value
----                           -----
PSVersion                      7.3.4
PSEdition                      Core
GitCommitId                    7.3.4
OS                             Microsoft Windows 10.0.19045
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Sorry for squished-up version info. The forum software has a mind of its own.

1

There are 1 best solutions below

0
On BEST ANSWER

Finally found a solution. I only wanted to see the sorted entries to confirm that my new file selection criteria (created/modified after a certain date) was working properly. It turns out Format-Table met that need. Here’s the code, if anyone’s interested:

    [System.IO.FileInfo[]] $queue = $null
    if ($true -eq $ignoreLastUploadDate) {
       $queue = Find-FilesNewOrChangedSinceLastUpload -ignoreLastUploadDate true
   } else {             
   here` $queue = Find-FilesNewOrChangedSinceLastUpload 
   }
   $fileCount = ($null -eq $queue ? 0 : [int]$queue.length)
   if ($fileCount -eq 0) {
      Write-Host "Found no new/changed files`n"
   } else {
      if ($false -eq $ignoreLastUploadDate) {               # If selected files by date
         $queue | Sort-Object -property lastWriteTime | `
         Format-Table -property name, lastWriteTime, length # Sort to verify date-time selection worked          
      }
   }
   $totalBytes = 0
   foreach ($file in $queue) {
      $totalBytes += $file.length
   }
   $suffix = $fileCount -eq 1 ? "" : "s"
   Write-Host $("`n{0:n0} file$suffix, {1:n0} bytes`n" -f $fileCount, $totalBytes)
   return $queue