我有一个带数字的目录列表。我需要找到最高的数字并将其加1,然后用该增量值创建一个新的目录。我能够对以下数组进行排序,但是我无法将最后一个元素递增,因为它是一个字符串。
如何将下面的数组元素转换为整数?
PS C:\Users\Suman\Desktop> $FileList
Name
----
11
2
1
我有一个带数字的目录列表。我需要找到最高的数字并将其加1,然后用该增量值创建一个新的目录。我能够对以下数组进行排序,但是我无法将最后一个元素递增,因为它是一个字符串。
如何将下面的数组元素转换为整数?
PS C:\Users\Suman\Desktop> $FileList
Name
----
11
2
1
您可以在变量之前指定其类型,以强制确定其类型。这被称为动态转换(此处有更多信息):
$string = "1654"
$integer = [int]$string
$string + 1
# Outputs 16541
$integer + 1
# Outputs 1655
作为示例,以下代码片段将在$fileList
中的每个对象上添加一个名为IntVal
的属性,该属性包含Name
属性的整数值,然后按照这个新属性(默认为升序)对$fileList
进行排序,并获取最后(具有最高IntVal
值)对象的IntVal
值,将其增加1,最后创建一个以该值命名的文件夹:# 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
)。2.032 MB (2,131,022 字节)
$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]
使用:
$filelist = @("11", "1", "2")
$filelist | sort @{expression={[int]$_}} | % {$newName = [string]([int]$_ + 1)}
New-Item $newName -ItemType Directory
使用:
$filelist = @(11, 1, 2)
$filelist | sort @{expression={$_[0]}} |
% {$newName = [string]([int]$($_[0]) + 1)}
New-Item $newName -ItemType Directory
$FileList | ` # Writes array to pipeline
Select-Object -Last 1 | ` # Selects last item in array
ConvertFrom-String -TemplateContent "{[int]NameTmp:12}" | ` # Converts string to number and names the variable "NameTmp"
Add-Member -Name "Name" -Value { $this.NameTmp + 1 } -MemberType ScriptProperty -PassThru | ` # Increments variable "NameTmp" by one and adds new variable named "Name" to pipeline object
New-Item -Type Directory # Creates new directy in current folder. Takes directory name from pipelined "Name" variable
一旦您选择了最高值,例如我的例子中的“12”,您可以将其声明为整数并增加您的值:
$FileList = "1", "2", "11"
$foldername = [int]$FileList[2] + 1
$foldername