I have a directory containing numbered directories:
Archive
|-1
|-2
|-3
|-...
I need to create the next directory numerically. For which I am currently doing
$lastArchive = ls .\Archive | sort Name | select -Last 1
$dirName = '1'
if($lastArchive) {
$dirName = ([int]$lastArchive.Name)+1
}
This of course fails once we get to 10 which by sorting rules follows after 1 not 9. I need the sort expression to actually be [int]$_.Name
- how would I do this?
Luckily, custom sorting is easy to accomplish in Windows PowerShell. To sort returned objects in Windows PowerShell, pipe the output from one cmdlet to the Sort-Object cmdlet. This technique is shown here where the Sort-Object cmdlet sorts the Process objects that are returned by the Get-Process cmdlet.
The Sort-Object cmdlet sorts objects in ascending or descending order based on object property values. If sort properties aren't included in a command, PowerShell uses default sort properties of the first input object.
The first way to do this is to use the Sort-Object cmdlet (Sort is an alias for the Sort-Object cmdlet). The second way to sort an array is to use the static Sort method from the System. Array .
To sort a hashtable, use the GetEnumerator() method on the hashtable to gain access to its individual elements. Then use the SortObject cmdlet to sort by Name or Value.
I think you need to change that first line as follows:
$lastArchive = ls .\Archive |
Sort-Object -property @{Expression={[int]$_.Name}} |
Select-Object -Last 1
Then, you can create the next directory in numerical order like this:
mkdir ([int]$lastArchive.Name + 1).ToString()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With