Как удалить 10 по давности файл через powershell

Sorting data should not be an overbearing task. If you are looking for an efficient way to sort data, the PowerShell Sort-Object cmdlet is here to help!

In this tutorial, you will learn how to use the PowerShell Sort-Object cmdlet to sort data, be it numbers, strings, or objects.

Scrap the constant eyeballing through your data and sort them efficiently in PowerShell!

powershell sort

One of the common tasks that PowerShell can perform is sorting data. Sorting data is an important function in data analysis, and it helps to make sense of large datasets. Understanding how to sort data can significantly enhance productivity and data management capabilities. It can be utilized for a multitude of applications, such as organizing logs, processing large data files, and creating detailed reports.

Introduction to PowerShell Sort

The PowerShell command Sort-Object is used to sort objects by their property values. Sorting, in computing, refers to arranging data in a particular format – either ascending or descending order. It can be used to sort data in virtually any format, including strings, numbers, and dates.

One of the great things about PowerShell is that it is incredibly easy to use. The cmdlets are built into PowerShell, so you don’t need to install any additional software to use it. You simply need to open a PowerShell window and start using the Sort-Object command.

Sort-Object
[[-Property] <Object[]>]
[-InputObject <psobject>]
[-Culture <string>]
[-CaseSensitive]
[-Descending]
[-Unique]
[-CaseSensitive]
[<CommonParameters>]

In the above syntax, -Property specifies the property or properties you want to sort by, and -Descending parameter specifies whether you would like to sort the data in descending order. The -Unique switch removes duplicate values and returns unique members of the collection as the result.

Всем доброго времени суток, я жуткий чайник в powershell скриптах, но стоит задача автоматизации бекапов. Встрял на таком моменте, мне нужно хранить 10 последних файлов каждой базы, если вдруг в какой-то день бекап не сделался в один из дней, то баз при очистке все равно должно остаться 10 (очистка по маске даты или просто по дате не подходит). Реализовывать это через цикл со счётчиком? Или есть ещё какие-то варианты? Если через счетчик, то как определить самый последний файл?


  • Вопрос задан

Добрый день.
То, что вам нужно можно сделать таким скриптом:

$files = Get-ChildItem -File -Path C:\temp | Sort-Object LastWriteTime
$count = $files.Count - 10
if ($count -gt 0) { $files | Select-Object -First $count | Remove-Item }

Но прежде чем применять его, проведите тестирование, что он удовлетворяет вашим требованиям

Вы забыли сказать, как именно берёте эти свои файлы
Если просто листинг папки, то после Get-ChildItem его можно отсортировать через Sort-Object -Descending -Property LastWriteTime
А потом, пропустив первые 10 (Select-Object -Skip 10), поудалять остальные


DBI

от 40 000 ₽

16 июл. 2024, в 11:20

10000 руб./за проект

16 июл. 2024, в 10:45

1500 руб./в час

16 июл. 2024, в 10:39

2000 руб./за проект


Often you may want to import data files into PowerShell and then sort the rows based on a specific column.

Method 1: Sort by String Column

This particular example imports the file specified at the path in the $my_file object, then sorts the rows in ascending order (A to Z) based on the values in the team column.

Note: By default, the Sort-Object cmdlet sorts values in ascending order. To instead sort by values in descending order, simply add the -descending operator at the end of the line.

Method 2: Sort by Numeric Column

This particular example imports the file specified at the path in the $my_file object, then sorts the rows in ascending order (smallest to largest) based on the values in the points column.

Example 1: How to Sort by String Column in PowerShell

Suppose we use the Import-Csv cmdlet to view the contents of this entire file:

Как удалить 10 по давности файл через powershell

The file contains three columns that show the team, points and assists for various basketball players.

Suppose that we would like to sort the rows by the strings in the team column.

PowerShell sort by string column in ascending order

Notice that the rows are now sorted in order from A to Z based on the strings in the team column.

If you would instead like to sort from Z to A, simply add the -descending operator at the end of the line:

PowerShell sort by string column in descending order

Notice that the rows are now sorted in order from Z to A based on the strings in the team column.

Example 2: How to Sort by Numeric Column in PowerShell

Suppose we use the Import-Csv cmdlet to view the contents of this entire file:

Как удалить 10 по давности файл через powershell

Suppose that we would like to sort the rows by the numeric values in the points column.

PowerShell sort by numeric column in ascending order

Notice that the rows are sorted in ascending order (smallest to largest) based on the value in the points column.

To instead sort the rows by the values in the points column in descending order (largest to smallest), simply add the -descending operator:

PowerShell sort by numeric column in descending order

Notice that the rows are now sorted in descending order (largest to smallest) based on the value in the points column.

PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Find Duplicate Values in Array
PowerShell: How to Compare Two Arrays

Recently, I got a requirement to sort an array alphabetically in PowerShell. PowerShell provides different methods for Sorting an array alphabetically. One of the simple and powerful cmdlet called Sort-Object for sorting a PowerShell array. In this blog post, we will explore how to use this cmdlet to sort an array alphabetically in PowerShell with complete examples.

Now, let us see different ways to sort an array alphabetically in PowerShell.

1. Using Sort-Object Cmdlet

The Sort-Object cmdlet is a versatile command in PowerShell that allows you to sort data in an array or a list based on object properties. By default, when you sort strings, it sorts them in ascending alphabetical order. Here’s a basic example:

# Create an array of strings
$names = 'Smith', 'Anderson', 'Wright', 'Mitchell'
# Sort the array alphabetically
$sortedNames = $names | Sort-Object
# Display the sorted array
$sortedNames

In this example, the output will display the names in alphabetical order: Anderson, Mitchell, Smith, Wright.

:/>  Как исправить хрипящий звук в Windows 10

I have executed the full PowerShell script using VS code, and you can see the output in the screenshot below:

Sort Array Alphabetically In PowerShell

2. Sort a PowerShell Array in Descending Order

If you want to sort the array in descending order in PowerShell, you can use the -Descending switch parameter:

Here is a complete PowerShell script:

# Create an array of strings
$names = 'Smith', 'Anderson', 'Wright', 'Mitchell'
# Sort the array in descending alphabetical order
$sortedNamesDesc = $names | Sort-Object -Descending
# Display the sorted array
$sortedNamesDesc

You can see the output in the screenshot below:

PowerShell Sort Array Alphabetically

3. Sort PowerShell Array Based on String Length

Here is the script to sort a string array alphabetically using string length in PowerShell.

# Create an array of strings
$names = 'Smith', 'Anderson', 'Wright', 'Mitchell'
# Sort the array based on string length
$sortedByLength = $names | Sort-Object { $_.Length }
# Display the sorted array
$sortedByLength

Here is the output you can see in the screenshot below:

powershell sort string array alphabetically

4. Case-Insensitive Sorting

By default, Sort-Object is case-insensitive when sorting strings in PowerShell. However, if you need to perform a case-sensitive sort, you can use the -CaseSensitive switch in PowerShell array.

# Create an array of strings
$names = 'Smith', 'Anderson', 'Wright', 'Mitchell'
# Case-sensitive alphabetical sort
$caseSensitiveSort = $names | Sort-Object -CaseSensitive
# Display the sorted array
$caseSensitiveSort

5. Sorting with Custom Comparisons

# Custom comparer for reverse alphabetical sorting
$comparer = [System.Collections.Generic.Comparer[string]]::Create({ param($x, $y) return [string]::CompareOrdinal($y, $x)
})
# Convert the array to a list
$list = [System.Collections.Generic.List[string]]$names
# Use the Sort method with the custom comparer
$list.Sort($comparer)
# Display the sorted list
$list

Conclusion

In this PowerShell tutorial, I have explained how to sort array alphabetically In PowerShell using different methods with examples.

You may also like:


Do you need to know about PowerShell sort arrays? In this PowerShell tutorial, I will explain how to sort an array in PowerShell using various methods and real examples.

An array is a data structure that holds a collection of items. These items can be of any data type, and in PowerShell, arrays can even hold items of different types. Arrays are incredibly useful for storing and manipulating sets of data.

Let us explore different methods to sort a PowerShell array.

Sorting a PowerShell Array with Sort-Object

The primary cmdlet for sorting in PowerShell is Sort-Object. This cmdlet sorts objects in ascending or descending order based on object property values. If you don’t specify a property, PowerShell will sort based on the default property for the object type.

Basic Sorting

Here’s a simple example of sorting an array of numbers in PowerShell using sort-object:

$array = 3, 1, 4, 1, 5, 9, 2
$sortedArray = $array | Sort-Object
$sortedArray

This will output the numbers in ascending order:

1
1
2
3
4
5
9

Here is another example of how to sort a string array in PowerShell.

# Define a string array
$stringArray = 'orange', 'apple', 'banana'
# Sort the array in ascending order using Sort-Object
$sortedArray = $stringArray | Sort-Object
# Output the sorted array
$sortedArray

This script will output the strings ‘apple’, ‘banana’, and ‘orange’ in ascending alphabetical order. You can see the output in the screenshot below after I executed the PowerShell script using VS code:

Sort an Array in PowerShell

If you wanted to sort in descending order, you would modify the Sort-Object line to include the -Descending parameter:

# Sort the array in descending order
$sortedArray = $stringArray | Sort-Object -Descending

You can see the output in the screenshot below; I have used VS code; you can use any editor to execute the PowerShell script.

PowerShell sort array

Sorting in Descending Order

To sort a PowerShell array in descending order, use the -Descending switch:

$sortedArray = $array | Sort-Object -Descending
$sortedArray

Sort String Array in PowerShell

You can also sort a string array in PowerShell. By default, the sort is case-insensitive:

$stringArray = 'Banana', 'apple', 'Cherry'
$sortedStringArray = $stringArray | Sort-Object
$sortedStringArray

This sorts the strings in alphabetical order:

apple
Banana
Cherry

Sort an Array in PowerShell using Custom Expression

Let us see how to sort an array in PowerShell using a custom expression. You can sort based on expressions, such as parts of a string or mathematical calculations:

$array = 'a1', 'a10', 'a2', 'a3'
$sortedArray = $array | Sort-Object { [int]($_.Substring(1)) }
$sortedArray

This will sort the array based on the numerical part of each string:

a1
a2
a3
a10

Sort a PowerShell Array with Multiple Properties

You can also sort a PowerShell array by multiple properties. This is useful when you have complex objects, and you want to sort by one property, then another:

$people = @( @{ Name = 'John'; Age = 30 }, @{ Name = 'Jane'; Age = 25 }, @{ Name = 'John'; Age = 22 }
)
$sortedPeople = $people | Sort-Object -Property Name, Age
$sortedPeople

The above PowerShell script will sort people by name and then by age within each name.

Sort Array with Hash Tables in PowerShell

Let me show you how to sort an array with hash tables in PowerShell.You can use hash tables to specify different sorts for different properties:

$sortedPeople = $people | Sort-Object -Property @{Expression="Name";Descending=$false}, @{Expression="Age";Descending=$true}
$sortedPeople

This sorts by name in ascending order and then by age in descending order.

Conclusion

Sorting arrays in PowerShell is a very common requirement, and we can achieve it using various methods. The Sort-Object cmdlet is the go-to for most sorting tasks, with options for sorting in ascending or descending order, case sensitivity, and unique value sorting.

In this PowerShell tutorial, I have explained how to work with PowerShell array sorting, especially different methods to sort a PowerShell array.

Yu may also like:

Sorting and Filtering Data in PowerShell Using ‘Sort-Object’

$Employees = Import-Csv -Path "C:\Temp\Employees.csv"
$SortedAndFilteredEmployees = $Employees | Where-Object { $_.Salary -gt 5000 } | Sort-Object -Property Salary
$SortedAndFilteredEmployees | Format-table

This command will filter the employees based on the salary threshold and then sort them in ascending order.

:/>  Пропал рабочий стол в Windows 10

Wrapping up

Sorting data is a fundamental skill in PowerShell that allows you to organize and analyze information effectively. By using the Sort-Object cmdlet, you can sort data in ascending or descending order and sort by multiple columns. Sorting data in ascending or descending order allows you to arrange information systematically.

Whether you are working with arrays, objects, or data in columns, PowerShell Sort provides a simple and versatile solution for sorting your data. By mastering the techniques outlined in this comprehensive guide, you can take your PowerShell skills to the next level and become a more efficient and effective professional. 

What is the purpose of the Sort-Object cmdlet in PowerShell?

The Sort-Object cmdlet is used to sort objects in PowerShell based on one or more properties. It allows you to sort input objects in ascending or descending order and can be used with various types of objects, such as strings, numbers, and custom objects.

How do I sort a list of items in PowerShell?

How do I sort an array in PowerShell?

How do I sort a file’s contents?

Can I sort data in a specific culture?

How do I sort objects by a specific property?

How do I sort in descending order?

Can I sort on multiple properties?

Can I sort objects based on a calculated property or expression?

Sorting by Multiple Columns

You can also sort data by multiple columns using PowerShell Sort. To sort data by multiple properties, you need to specify the properties you want to sort by, separated by commas.

Get-ChildItem -File | Sort-Object -Property Name, Length

This command will list all the files in the current directory, sorted by name and then by size, in ascending order.

You can also sort using expressions:

Get-Service | Sort-Object -Property @{expression = 'Status';descending = $true}, @{expression = 'DisplayName';descending = $false}

In the above script, The Get-Service cmdlet gets a list of services on the computer and sends them down to the pipeline to sort-object. The Sort-Object cmdlet sorts them based on property parameters.

Sorting Data by Unique Values

Sorting data in ascending and descending order is one thing. But there may be instances where you need to sort data based on unique values. In this context, “unique” refers to distinct or non-repeated values within a dataset.

To sort data by unique values:

  • Define a list of integer numbers (with duplicates included) in the $numbers variable.
  • Sort the numbers by -Unique values in -Descending order and store the result in the $sortedNumbers variable.

When sorting by unique values, you arrange the data so that each value appears only once in the sorted result, eliminating duplicates.

$numbers = 4, 2, 3, 3, 1, 5, 2
$sortedNumbers = $numbers | Sort-Object -Unique -Descending

Now, run the Write-Output command below to output the contents of the $sortedNumbers variable to verify the result.

Write-Output $sortedNumbers

Below, all unique values are sorted in descending order, and duplicate values have been eliminated.

As you can see, sorting by unique values enhances data analysis efficiency and eliminates redundant information when dealing with large datasets.

powershell sort-object -Sorting data by unique values
Sorting data by unique values

Common Pitfalls and Troubleshooting Tips for Sorting Data in PowerShell

While sorting data in PowerShell is generally straightforward, you may encounter a few common pitfalls and issues. Here are some troubleshooting tips to help you overcome them:

  1. Ensure that the property you are sorting by exists in the data structure you are working with. The sorting operation fails if you misspell the property or it doesn’t exist.
  2. Be aware of the data type of the property you are sorting by. If the data type is incompatible with the sorting operation, sorting may produce unexpected results.
  3. Check for any formatting or encoding issues that may affect the sorting order. Make sure to format the data correctly and handle any special characters or accents properly.
  4. If you encounter performance issues when sorting large datasets, consider optimizing your code by using more efficient algorithms or techniques, such as parallel processing or hash tables for indexing.

Sorting Data by Strings

So far, you have seen how to sort numeric values. But what if you are working with strings? Worry not. The Sort-Object cmdlet lets you arrange string data in a specific order based on sorting criteria.

In this context, a string refers to a single character or a sequence of characters, such as words, phrases, or other textual data. In PowerShell, strings are represented by enclosing the text within quotation marks, either single (') or double (").

Sorting strings in PowerShell provides flexibility in organizing textual data in a desired order, allowing efficient data manipulation and analysis.

# Define an array of strings
$strings = "a", "b", "c"
# Sort the strings in ascending order by default (no parameters)
$sortedStrings = $strings | Sort-Object
# Display the sorted strings
Write-Output $sortedStrings
Sorting strings in alphabetical order
Sorting strings in alphabetical order

Now, run the same commands, but sort them in -Descending order instead.

# Define an array of strings
$strings = "a", "b", "c"
# Sort the strings in descending order
$sortedStrings = $strings | Sort-Object -Descending
# Display the sorted strings
Write-Output $sortedStrings

This time you will see the output in the reverse order, as shown below.

Sorting strings in the reverse order
Sorting strings in the reverse order

Sorting Hash Tables

Sorting objects by properties is a game-changer when working with data analysis. But what about organizing data in key-value pairs like hash tables?

The Sort-Object cmdlet lets you sort hash tables to enhance data presentation and simplifies information retrieval.

# Create a hash table with three key-value pairs
$hashTable = @{ "C" = "Charlie" "A" = "Alpha" "B" = "Bravo"
}
# Sort the hash table by keys and store the sorted result in $sortedHashTable
$sortedHashTable = $hashTable.GetEnumerator() | Sort-Object -Property Name
# Iterate through each entry in the sorted hash table
foreach ($entry in $sortedHashTable) { # Output the key-value pair Write-Output "$($entry.Name): $($entry.Value)"
}

This sorting method ensures better data presentation and makes retrieving information from the hash table easier.

Sorting hash tables
Sorting hash tables

Sorting Data by Properties

No doubt sorting string comes in handy. But typically, you should be more specific when sorting data. In addition to sorting strings, why not sort objects based on their properties?

:/>  Winsatassessmentstate 1 что это значит

When working with PowerShell objects, each object typically possesses one or more properties you can use for sorting. These properties allow you to define your sorting criteria tailored to your needs.

# Retrieve a collection of all running processes
$processes = Get-Process
# Sort the processes based on CPU usage in descending order
$sortedProcesses = $processes | Sort-Object -Property CPU -Descending
# Select and display the Name and CPU properties of each process
$sortedProcesses | Select-Object Name, CPU
Sorting data by properties
Sorting data by properties

Sorting Data with the PowerShell Sort-Object cmdlet

Depending on your requirements, you can sort data based on one or more properties in many ways. The Sort-Object cmdlet allows you to sort data, for example, in ascending or descending order to ease analyzing and working with structured information.

  • <Object-to-Sort> – Refers to collecting data to sort, such as an array, a list, or other data types.
  • <-Parameter> – An optional parameter to specify the sorting criteria that allows you to customize how the sorting is performed.
<Object-to-Sort>|Sort-Object <-Parameter>

To see how you can sort data in ascending and descending order:

1. Open PowerShell and run the below command, which does not provide output but defines a list of random integer numbers in the $numbers variable.

💡 Note that in PowerShell, you are not just working with numbers and strings but objects since PowerShell is an object-oriented language and shell.

$sortedNumbers = $numbers | Sort-Object
Write-Output $sortedNumbers

Without appending parameters, the output displays the numbers in ascending order.

Как удалить 10 по давности файл через powershell
Sorting data in ascending order

3. Now, run the same commands, but this time, append the -Descending parameter to sort and display the numbers in descending order.

$sortedNumbers = $numbers | Sort-Object -Descending
Write-Output $sortedNumbers

The output similar to the one below indicates the numbers have been sorted in descending order.

Sorting numbers in descending order
Sorting numbers in descending order

Sorting Objects with Specific column in PowerShell

In addition to sorting arrays, you can also use PowerShell Sort to sort objects. An object is a collection of properties that are stored in a variable. You can use PowerShell Sort-Object to sort objects based on one or more of their properties.

$objects | Sort-Object Name

Sorting CSV Data by a Specific Column in PowerShell

When working with structured data, such as CSV files or arrays of objects, you often need to sort data by a specific column. PowerShell provides a convenient way to do this using the ‘Sort-Object’ cmdlet. For example, let’s say you have a CSV file containing employee information, including their names and salaries.

sorting in powershell
Employee ID,First Name,Last Name,Designation,Department,Age,Salary
1,John,Doe,Manager,IT,45,80000
2,Jane,Smith,Developer,Sales,34,70000
3,James,Johnson,Designer,IT,28,60000
4,Emily,Williams,Analyst,Sales,30,65000
5,Michael,Brown,CEO,HR,55,120000
6,Linda,Jones,CTO,IT,50,115000
7,Robert,Miller,IT,Developer,32,70000
8,Elizabeth,Davis,HR,Manager,40,55000
$Employees = Import-Csv -Path "C:\Temp\Employees.csv"
$SortedEmployees = $Employees | Sort-Object -Property Salary
$SortedEmployees | Format-table

This command will sort the employees based on their salaries, arranging them in ascending order. If you want to sort them in descending order, you can add the ‘-Descending’ parameter.

PowerShell sort-object

Sorting and Grouping in PowerShell

Another powerful feature of PowerShell Sort is the ability to sort and group data simultaneously. This can be especially useful when working with large datasets that need to be organized into smaller groups.

Import-Csv "C:\Temp\Employees.csv" | Group-Object Department | ForEach-Object { $_.Group | Sort-Object Salary }
sort array powershell

Sorting Data in Arrays Using PowerShell

$numbers = 5, 2, 8, 1, 10
$sortedNumbers = $numbers | Sort-Object
Get-Process | Sort-Object Name
Get-Process | Sort-Object CPU -Descending

This will sort the list of processes by CPU utilization in descending order.

PowerShell Sort-Object Real-World Examples

Here are a few examples to give you a better idea of how you can use PowerShell Sort in real-world scenarios:

Example 1: Sorting Files by Created Date

Get-ChildItem -Path "C:\Temp" | Sort-Object LastWriteTime -Descending

Example 2: Sorting a List of Names by Length

Suppose you have a list of names, and you want to sort the names by length. You can do this using a custom sorting algorithm that counts the number of characters in each name:

$names = "Alice", "Bob", "Charlie", "David"
$names | Sort-Object { $_.Length }

Example 3: Sorting Object Array

$employees = @( [PSCustomObject]@{Name='Emma'; Age=30}, [PSCustomObject]@{Name='Oliver'; Age=35}, [PSCustomObject]@{Name='Liam'; Age= 25}, [PSCustomObject]@{Name='Ava'; Age=32}, [PSCustomObject]@{Name='Sophia'; Age=28}
)
$Employees | Sort-Object -Property Age

This will output the list of employees, sorted in ascending order by age.

Sorting Data in Hashtables Using PowerShell

$countries = @{ "USA" = 328.2 "China" = 1439 "India" = 1380 "Brazil" = 209.3
}
$sortedCountries = $countries.GetEnumerator() | Sort-Object -Property Value
$sortedCountries

This command will sort the countries based on their populations, arranging them in ascending order.

Sorting Unique Values in PowerShell

$numbers = 5, 2, 8, 1, 10, 5, 2
$uniqueNumbers = $numbers | Sort-Object -Unique

Conclusion

Throughout this tutorial, you have explored how to sort unique values, strings, numbers, processes, and even hash tables with the Sort-Object cmdlet. Data sorting is one task that lets you pave the way to a more insightful data analysis, and with the PowerShell Sort-Object cmdlet, you are on the right track.

Armed with this newfound knowledge, you can now ensure your data is organized meaningfully and confidently showcase it to others.

Sorting is just one of the many valuable capabilities of PowerShell and its cmdlets. Why not expand your skills by learning about other cmdlets? Perhaps create program logs with Tee-Object or measure object sizes with Measure-Object?

Sorting Data in Ascending Order in PowerShell

sorting in powershell-min

Ascending order sorting is a fundamental technique for arranging data from the smallest to the largest value. Sorting data in ascending order is the default behavior of the ‘Sort-Object’ cmdlet in PowerShell. However, you can explicitly specify the ascending order using the ‘-Ascending’ parameter. Suppose we have a simple array of numbers that we want to sort in ascending order. Here’s how we’d do it:

# PowerShell sort array - Example
$Numbers = @(1, 2, 4, 3, 6, 5, 7)
$Numbers | Sort-Object

Sorting String Array Alphabetically in PowerShell

$names = "John", "Alice", "David", "Bob"
$sortedNames = $names | Sort-Object

Sorting Data in Descending Order in PowerShell

$numbers = 5, 2, 8, 1, 10
$sortedNumbers = $numbers | Sort-Object -Descending
$sortedNumbers
Get-ChildItem -Path "C:\Temp\*.txt" | Sort-Object -Property $_.CreationTime -Descending

Let’s sort files from all subdirectories from a given path, by File length:

Get-ChildItem "C:\Temp" -Recurse -File | Sort-Object -Property Length | Out-GridView