기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

버즈 라이브 배터리 교체

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

ESP8266 + TM1637 WIFI 인터넷 시계 만들기

ESP8266 과 TM1637 으로 인터넷 시계 만들기 원래는 다이소에서 판매하는 5000원짜리 시계 뜯어서 만드려고 했는데, 시계를 뜯어보니, 자체 MCU를 통해 제어를 하고 있어 TM1637 로 구현하고 나중에 케이스를 만드는게 나을 것 같아서 아래와 같이 구현(chatGPT)했다. 30분마다 NTP 가져오기 WIFI가 끊기더라도 RTC 유지 WIFI가 끊기면 1분에 한 번씩 재접속 시도 버튼을 3초 누르면, AP 설정 모드 (88:88 표시) #include <ESP8266WiFi.h> #include <WiFiUdp.h> #include <TM1637Display.h> #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager #define CLK D5 // TM1637 CLK #define DIO D6 // TM1637 DIO #define CONFIG_BUTTON_PIN D7 // 설정 진입 버튼 TM1637Display display(CLK, DIO); // 시간 관련 변수 time_t currentEpochTime = 0; unsigned long lastNtpMillis = 0; unsigned long checkTermMillis = 1800000UL; // 30분마다 NTP 다시 받아옴 // Wi-Fi 재접속 관련 unsigned long lastWiFiReconnectAttempt = 0; const unsigned long wifiReconnectInterval = 60000; // 1분 // 버튼 관련 unsigned long buttonPressedTime = 0; bool buttonWasHeld = false; const unsigned long CONFIG_HOLD_TIME = 3000; // 3초 bool isInConfigMode = false; const char* ntpServer = ...

Windows 에서 절전을 깨우는 장치 찾기

참조:  https://www.reddit.com/r/computer/comments/wquswv/windows_11_pc_wakes_up_every_time_i_move_usb/ powercfg /devicequery wake_armed powercfg /deviceenablewake "[DEVICE]" # $PROFILE function Get-WakeArmedDevices { $devices = powercfg -devicequery wake_armed if ($devices) { $devices | ForEach-Object { $_.Trim() } } else { Write-Host "No devices are currently armed for wake events." } } function Set-EnableWakeOnDevice { param( [string]$deviceName ) sudo powercfg -deviceenablewake $deviceName } function Set-DisableWakeOnDevice { param( [string]$deviceName ) sudo powercfg -devicedisablewake $deviceName }