I have a list of directories with numbers. I have to find the highest number and and increment it by 1 and create a new directory with that increment value. I am able to sort the below array, but I am not able to increment the last element as it is a string.
How do I convert this below array element to an integer?
PS C:\Users\Suman\Desktop> $FileList Name ---- 11 2 1
The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.
You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):
$string = "1654" $integer = [int]$string $string + 1 # Outputs 16541 $integer + 1 # Outputs 1655
As an example, the following snippet adds, to each object in $fileList
, an IntVal
property with the integer value of the Name
property, then sorts $fileList
on this new property (the default is ascending), takes the last (highest IntVal
) object's IntVal
value, increments it and finally creates a folder named after it:
# For testing purposes #$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" }) # OR #$fileList = New-Object -TypeName System.Collections.ArrayList #$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null $highest = $fileList | Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } | Sort-Object IntVal | Select-Object -Last 1 $newName = $highest.IntVal + 1 New-Item $newName -ItemType Directory
Sort-Object IntVal
is not needed so you can remove it if you prefer.
[int]::MaxValue = 2147483647
so you need to use the [long]
type beyond this value ([long]::MaxValue = 9223372036854775807
).
Example:
2.032 MB (2,131,022 bytes)
$u=($mbox.TotalItemSize.value).tostring() $u=$u.trimend(" bytes)") #yields 2.032 MB (2,131,022 $u=$u.Split("(") #yields `$u[1]` as 2,131,022 $uI=[int]$u[1]
The result is 2131022 in integer form.
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