기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

Winget 해시 무시하기

가끔씩 Winget 에서 패키지를 다운로드 했을 때, "설치 관리자 해시가 일치하지 않습니다." 오류가 뜰 때가 있다. 보안 이슈가 있지만, 그냥 무시하고 싶을 때, 아래 순서로 무시해준다. 관리자 권한 winget settings --enable InstallerHashOverride 설치 winget install --ignore-security-hash --id NirSoft.NirCmd

Windows 11 기존 컨텍스트 메뉴 사용

Windows 11 에서, 컨텍스트 메뉴가 지저분한게 싫었는지, 모던 컨텍스트 메뉴라고 따로 필요한 것만 정리해서 보여준다. 그러나 이게 좀 불편하고, 기존의 꼭 필요한 메뉴가 보이지 않아 굳이 한 번 더 기존 메뉴를 불러오는데, 모든 앱들이 모던 컨텍스트 메뉴로 옮길 때까지는 기존 컨텍스트 메뉴를 기본으로 볼 수 있는 방법이 있다. REM 관리자 권한 REM 기존 컨텍스트 메뉴 reg.exe add "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" /f /ve REM 모던 컨텍스트 메뉴로 되돌리기 reg.exe delete "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}" /f 이거 하고 탐색기를 재시작한다. 참조:  Restore old Right-click Context menu in Windows 11