기본 콘텐츠로 건너뛰기

Powershell Array, Map 정리

Powershell에서 Array, Map에 대한 정리. (매번 찾기 귀찮)

Array
참조: 배열에 대해 알고 싶은 모든 것
# 생성
$empty_array = @()
$ar = @("haha", "hoho", "baba", "long string haha hoho")
# $ar = "hello", "world, "byebye"

# 접근
Write-Output "`$ar[0]=$($ar[0])"

Write-Output "all as array=$($ar)" # 기본
Write-Output "all as one=$($ar -join ' ')" # 띄어쓰기를 포함하여 문자열로 합치기
Write-Output "all as one=$(-join $ar)" # 띄어쓰기 없이 문자열로 합치기

Write-Output "length=$($ar.Count)"

Write-Output "last=$($ar[-1])"

# 현재 상황
Write-Output $ar

$ar[-1] = "last"
Write-Output $ar # 마지막 원소를 지우고 대입한다.

$ar[-2] = "whoami"
Write-Output $ar # 마지막-1 원소를 지우고 대입한다.

# 추가
$ar += @("blar")
$ar += @("keke", "123", "456")
$ar += @("long long long string", "another long long long string")
Write-Output $ar

# Powershell은 Array에 대해 삭제를 지원하지 않으며, List 객체를 사용할 것
# List 등 Generic Collection을 사용하기 위해 아래 구문을 스크립트 맨위에 추가할 것 (마치 import, include 처럼)
using namespace System.Collections.Generic

$lst = [List[string]]@("1st", "2nd", "3rd", "last")
$lst.Remove("3rd")
# Write-Output $lst

# 루프1
for ($i = 0; $i -lt $ar.Count; ++$i) {
    Write-Output $ar[$i]
}

# 루프2
foreach ($node in $ar) {
    Write-Output $node
}
Map

# 생성
$empty_map = @{}
$map = @{hello = "world"; long = "long long long string"; "what is it" = 123 }
Write-Output $map

Write-Output "map[hello]=$($map["hello"])"
$key = "hello"
Write-Output "map[key]=$($map[$key])"

Write-Output "keys=$($map.Keys)"
Write-Output "values=$($map.Values)"
Write-Output "length=$($map.Count)"

# 추가
$map += @{key1 = "value"; key2 = "value2" }
$map.Add("key3", "value3")
$map["like a C++"] = "value!!!!!"
Write-Output $map

# 루프1
foreach ($value in $map.values) {
    Write-Output $value
}

# 루프2
foreach ($key in $map.Keys) {
    Write-Output $map[$key]
}

# 루프3
$map.GetEnumerator() | ForEach-Object {
    Write-Output "$($_.Key) = $($_.Value)"
}

# 제거
$map.Remove("key3")
Write-Output $map

# Json
$map | ConvertTo-Json

댓글

이 블로그의 인기 게시물

탐색기에서 OneDrive 이 2개로 보이는 문제

왜 2개가 보이는지 모르겠지만, Registry 삭제하면 됨 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace 하위 키에서 OneDrive 둘 중에 하나만 지워도 바로 반영됨. 참조:  https://answers.microsoft.com/en-us/msoffice/forum/all/duplicate-onedrives-in-file-explorer/49c935a6-287b-43a5-aed5-2dee2a1c1b22