source

PowerShell에서 문자열을 정수로 변환하는 방법

nicesource 2023. 4. 14. 21:53
반응형

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) 객체의IntValvalue, 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

반응형