问题描述
我有一个带数字的目录列表.我必须找到最大的数字并将其增加 1 并创建一个具有该增量值的新目录.我能够对下面的数组进行排序,但我无法增加最后一个元素,因为它是一个字符串.
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
推荐答案
您可以在变量之前指定类型以强制其类型.这称为(动态)转换(更多信息在此处):
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
作为示例,以下代码段向 $fileList
中的每个对象添加了一个 IntVal
属性,其中包含 Name
的整数值属性,然后在这个新属性上对 $fileList
进行排序(默认为升序),取最后一个(最高的 IntVal
)对象的 IntVal
值,递增最后创建一个以它命名的文件夹:
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
不是必需的,因此您可以删除它如果您愿意.
Sort-Object IntVal
is not needed so you can remove it if you prefer.
[int]::MaxValue = 2147483647
所以你需要使用超出这个值的 [long]
类型 ([long]::MaxValue = 9223372036854775807
).
[int]::MaxValue = 2147483647
so you need to use the [long]
type beyond this value ([long]::MaxValue = 9223372036854775807
).
这篇关于如何在PowerShell中将字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!