기본 콘텐츠로 건너뛰기

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

버즈 라이브 배터리 교체

나는 버즈 라이브(SM-R180)가 좋은데, 평가가 별루였는지, 해당 스타일로 버즈를 더 이상 만들지 않고 있다. 아무튼, 오래 쓴 버즈 라이브 배터리가 슬슬 맛이 가기 시작해서, 블로그 를 참조하면서 분해 및 교체를 하였다. (진짜 쉬움) 요로코롬 위아래를 살짝 눌러주면 뚜껑이 벌어진다. 안쪽 플라스틱은 오른쪽은 분홍색, 왼쪽은 회색이다. 리본 케이블 살짝 들어내고, 기판을 떼어내면, 작은 나사가 있다. 나사를 풀고, 플라스틱을 걷어내면, 검은 양면 테이프로 고정된 CR1254 배터리가 보인다. 잘 쑤셔서(?) 꺼낸다. 새로운 CR1254 배터리를 넣는다. 음극이 아래로 가도록 하고, 분해의 역순으로 조립하면 된다. 조립할 때, 아까 풀었던 나사는 잊지 말고 꼭 조여준다. (까먹고 조립해서 다시 뜯고 조립함) 충전도 잘 되고, 소리도 잘 나는거 보면, 조립도 잘 된 것 같다. 이렇게 버즈 라이브의 수명을 강제로 늘렸다. 나중에 본체 배터리도 갈아야겠다.