On Windows 10 or Windows 11, use Windows PowerShell 5.1 to read a CSV with
Import-Csv, keep matching rows with Where-Object, and order them with Sort-Object. CSV values come in as text, so sort a quantity using a numeric expression such as { [int]$_.Units }, not just the column name. Once the preview looks right, use Export-Csv with a new filename and -NoClobber. The original file stays untouched, and PowerShell won’t overwrite an earlier export.
Prepare the CSV and check its headings
Allow about 15 minutes for a first run. You need permission to read the input file and save a new file in the destination folder. You don’t need Excel, administrator rights, a script file, or a restart. Keep the same PowerShell window open throughout so the rows you inspect are the ones you export.
- Open Windows PowerShell. On either Windows version, press Windows key + R, type
powershell.exe, and press Enter. Run$PSVersionTable.PSVersionand check that Major is5and Minor is1. These instructions use the built-in Windows shell, not the separately installed PowerShell 7. - Choose a CSV with a header row. The example below keeps the
Openorders and sorts them from the largest quantity to the smallest. Use your own CSV and substitute its headings and values, or copy the following text into Notepad for a practice run. To save the sample, choose File > Save As, select a folder you can write to, set Save as type to All files, and enterorders-practice.csvas the filename. Choose a different name if that file already exists.
The sample has two useful checks: the largest order overall is closed, so it should disappear; and the largest open order hasCode:OrderID,Status,Units A101,Open,9 A102,Closed,200 A103,Open,100 A104,Open,20 A105,Closed,3100units, so it should finish ahead of both20and9. - Import the file by its full path. Replace the example path inside the quotes with the actual location of your CSV. The first command names the source; the second reads it.
-LiteralPathtreats characters such as square brackets in a filename literally. The@(...)keeps the result as a collection even if there is only one data row.
For the sample, expect a count ofCode:$source = 'C:\Users\Pat\Documents\orders-practice.csv' $rows = @(Import-Csv -LiteralPath $source -ErrorAction Stop) $rows.Count $rows | Select-Object -First 3 | Format-Table -AutoSize5and a preview with three separate headings:OrderID,Status, andUnits. The header is not a sixth record. Stop here if the headings are wrong. A filter that refers to a missing column can return no rows rather than an obvious spelling error. For a wide file, run$rows[0].PSObject.Properties.Nameto list the headings one per line, provided the row count is greater than zero.
Filter the rows, then sort by the right kind of value
- Keep only rows that match the condition. In this command,
$_means the row currently being examined,.Statusreads its status field, and-eqtests for equality. The result goes into a new variable;$rowsstill contains the full import.
Expect three rows:Code:$matchesOnly = @($rows | Where-Object { $_.Status -eq 'Open' }) $matchesOnly.Count $matchesOnly | Format-Table OrderID, Status, Units -AutoSizeA101,A103, andA104. Their order hasn’t changed yet. For your own file, change both parts of the comparison: for example, use{ $_.Department -eq 'Sales' }to keep the sales department. If the heading contains a space, quote the whole heading after the dot:{ $_.'Order Status' -eq 'Open' }. The normal PowerShell text comparison ignores letter case, soOPENalso matchesOpen. - Sort the matches by quantity. For the sample’s whole-number quantities, use the command below. It converts each
Unitsvalue to an integer for the comparison, and-Descendingputs the largest first. It does not replace the field or discard the other columns.
The expected order isCode:$result = @($matchesOnly | Sort-Object -Property { [int]$_.Units } -Descending -ErrorAction Stop) $result | Format-Table OrderID, Status, Units -AutoSizeA103(100),A104(20), thenA101(9). Without the conversion, descending text order would put9first: PowerShell would be comparing initial characters, not amounts. Omit-Descendingif you want smallest first. If your chosen column is a name rather than a quantity, no conversion is needed; for example,$result = @($matchesOnly | Sort-Object -Property Customer)sorts by aCustomerheading in ascending order.
Use the integer expression only for whole numbers that fit in a 32-bit signed integer. Don’t use it for prices with cents or identifiers such as postal codes. If a quantity is missing, decide whether the row belongs in the report before sorting: a blank is not evidence that the quantity was zero.
Export to a new file and verify what was saved
- Save the result, not the formatted preview. The command below chooses a destination beside the input file. It stops if there are no matching rows rather than creating an apparently successful empty report. Check the displayed destination before running the export line.
KeepCode:$destination = Join-Path (Split-Path -Parent $source) 'open-orders-by-units.csv' $destination-NoClobberin the export command. Without it,Export-Csvcan replace an existing file. If the destination is already in use, choose a fresh filename rather than removing the safeguard.
Code:if ($result.Count -eq 0) { throw 'No rows to export. Check the filter first.' } $result | Export-Csv -LiteralPath $destination -NoTypeInformation -Encoding UTF8 -NoClobber -ErrorAction Stop-NoTypeInformationmakes the column names the first line instead of adding a Windows PowerShell type-information line above them. Explicit UTF-8 output preserves characters such as accented customer names. Export directly from$result:Format-Tableis useful on screen, but its output describes a display layout, not the original records. - Read the saved file back. A successful export need not print a confirmation. After the export completes without an error, run:
For the practice file, both counts should beCode:$saved = @(Import-Csv -LiteralPath $destination) "Saved rows: $($saved.Count); expected: $($result.Count)" $saved | Select-Object -First 10 | Format-Table -AutoSize3, the headings should still beOrderID,Status, andUnits, and the first order should beA103. For your own file, check the filter column and the first few sort values as well as the count. A matching count alone won’t catch a sort in the wrong direction. If you need to undo the export, remove only the new file in File Explorer after checking its full path. There is nothing to restore in the source CSV.
Troubleshoot missing matches, incorrect order, or export errors
- The preview has one heading containing semicolons. This is a delimiter mismatch, not a filter problem. Inspect the first line in Notepad. If it reads
OrderID;Status;Units, repeat the import as$rows = @(Import-Csv -LiteralPath $source -Delimiter ';' -ErrorAction Stop), then rerun the filter and sort. If the recipient also needs semicolon-separated output, add-Delimiter ';'to both the export and the verification import. A.csvextension alone does not tell PowerShell which separator to use. - The headings look right, but no rows match. Run
$rows | Group-Object -Property Status | Select-Object Count, Nameto see which status values actually occur. Your file may sayActiverather thanOpen, or its values may contain extra spaces. If spaces are the issue, use{ ([string]$_.Status).Trim() -eq 'Open' }in the filter. Trimming for the comparison leaves the original field intact. Rerun the sort after changing the filter;$resultdoes not update automatically. - The numeric sort reports a conversion error or puts blank quantities among real ones. For the sample’s nonnegative whole-number format, run
$matchesOnly | Where-Object { $_.Units -notmatch '^[0-9]+$' } | Format-Table OrderID, Units. This identifies blanks, labels such asN/A, and values that don’t follow that format. If a value contains digits only but exceeds2147483647,[int]is too small; use[long]if the value fits a signed 64-bit integer. Don’t strip punctuation indiscriminately to make the command succeed:12.50and1250are different quantities. - PowerShell says the destination exists or access is denied. An existing-file error means the overwrite protection worked. Change the filename in
$destinationand rerun the export. If you can read the source but cannot write beside it, set$destinationto a full filename in a folder you can write to. Don’t verify the old destination after a failed export: a perfectly readable CSV at that path could be yesterday’s report. - The saved CSV has unexpected columns or damaged names. Columns describing formatting rather than orders usually mean
Format-Tablewas piped intoExport-Csv. Export$resultdirectly to a new filename. For damaged characters, compare a name in$rowswith the same name in$saved. If the import already looks wrong, changing the export encoding cannot repair it. Confirm the source encoding with the application that produced the file, reimport with the matching-Encoding, and repeat the filter, sort, and read-back check.