PowerShell에서 문자열을 정수로 변환하는 방법
전화번호부 목록이 있어요가장 높은 숫자를 찾아서 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
, anIntVal
의 정수 값을 가진 속성Name
속성, 다음으로 정렬$fileList
이 새 속성(기본값은 오름차순)에서 마지막(가장 높음)을 가져옵니다.IntVal
) 객체의IntVal
value, value, increment, first folder는 value의 이름을 따서 만듭니다.
# 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]
결과는 정수형식의 2131022입니다.
용도:
$filelist = @(11, 1, 2)
$filelist | sort @{expression={$_[0]}} |
% {$newName = [string]([int]$($_[0]) + 1)}
New-Item $newName -ItemType Directory
용도:
$filelist = @("11", "1", "2")
$filelist | sort @{expression={[int]$_}} | % {$newName = [string]([int]$_ + 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
언급URL : https://stackoverflow.com/questions/33707193/how-to-convert-string-to-integer-in-powershell
'source' 카테고리의 다른 글
플랫 테이블을 트리로 해석하는 가장 효율적이고 우아한 방법은 무엇입니까? (0) | 2023.04.14 |
---|---|
패키지가 설치되어 있는지 확인하고 설치되어 있지 않으면 어떻게 해야 합니까? (0) | 2023.04.14 |
Swift Array에서 최소/최대값 검색 (0) | 2023.04.14 |
WPF WebBrowser 컨트롤을 사용할 때 스크립트 오류를 억제하려면 어떻게 해야 합니까? (0) | 2023.04.14 |
목표 C에서 NSAray를 되돌리려면 어떻게 해야 하나요? (0) | 2023.04.09 |