gpt4 book ai didi

powershell - 如何在 PowerShell 中将字符串转换为整数

转载 作者:行者123 更新时间:2023-12-03 06:05:08 25 4
gpt4 key购买 nike

我有一个带有数字的目录列表。我必须找到最大的数字,然后将其增加 1,并使用该增量值创建一个新目录。我可以对下面的数组进行排序,但无法增加最后一个元素,因为它是一个字符串。

如何将下面的数组元素转换为整数?

PS C:\Users\Suman\Desktop> $FileList

Name
----
11
2
1

最佳答案

您可以在变量之前指定变量的类型以强制其类型。这称为(动态)类型转换 ( more information is here ):

$string = "1654"
$integer = [int]$string

$string + 1
# Outputs 16541

$integer + 1
# Outputs 1655
<小时/>

作为示例,以下代码片段向 $fileList 中的每个对象添加一个 IntVal 属性,其中包含 Name 的整数值属性,然后在此新属性上对 $fileList 进行排序(默认为升序),采用最后一个(最高 IntVal)对象的 IntVal 值,递增它并最终创建一个以它命名的文件夹:

# 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 不是必需的,因此您可以将其删除如果您愿意

[int]::MaxValue = 2147483647 因此您需要使用超出此值的 [long] 类型 ([long]::MaxValue = 9223372036854775807 )。

关于powershell - 如何在 PowerShell 中将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com