PowerShell에는 연관 배열이 있습니까?
-
19-09-2019 - |
문제
ID, 이름 쌍을 반환하는 함수를 작성하고 있습니다.
나는 같은 일을하고 싶다
$a = get-name-id-pair()
$a.Id
$a.Name
JavaScript에서는 가능합니다. 아니면 적어도
$a = get-name-id-pair()
$a["id"]
$a["name"]
PHP에서 가능합니다. PowerShell과 함께 할 수 있습니까?
해결책
또한
$a = @{'foo'='bar'}
또는
$a = @{}
$a.foo = 'bar'
다른 팁
예. 다음 구문을 사용하여 작성하십시오
$a = @{}
$a["foo"] = "bar"
솔루션을 찾고 있었고 하나를 찾지 못했기 때문에 Hashtable을 통해 반복하는 방법도 추가 할 것입니다 ...
$c = @{"1"="one";"2"="two"}
foreach($g in $c.Keys){write-host $c[$g]} #where key = $g and value = $c[$g]
#Define an empty hash
$i = @{}
#Define entries in hash as a number/value pair - ie. number 12345 paired with Mike is entered as $hash[number] = 'value'
$i['12345'] = 'Mike'
$i['23456'] = 'Henry'
$i['34567'] = 'Dave'
$i['45678'] = 'Anne'
$i['56789'] = 'Mary'
#(optional, depending on what you're trying to do) call value pair from hash table as a variable of your choosing
$x = $i['12345']
#Display the value of the variable you defined
$x
#If you entered everything as above, value returned would be:
Mike
당신은 또한 이것을 할 수 있습니다 :
function get-faqentry { "meaning of life?", 42 }
$q, $a = get-faqentry
연관 배열은 아니지만 동일하게 유용합니다.
-이신
여러 도메인에서 작업 할 때 사이트/디렉토리를 추적하는 데 사용합니다. 각 항목을 개별적으로 추가하는 대신 배열을 선언 할 때 배열을 초기화 할 수 있습니다.
$domain = $env:userdnsdomain
$siteUrls = @{ 'TEST' = 'http://test/SystemCentre'
'LIVE' = 'http://live/SystemCentre' }
$url = $siteUrls[$domain]
PS C:\> $a = @{}
PS C:\> $a.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
따라서 해시 테이블은 연관 배열입니다. 오.
또는:
PS C:\> $a = [Collections.Hashtable]::new()
JSON 문자열에서 생성하십시오
$people= '[
{
"name":"John",
"phone":"(555) 555-5555"
},{
"name":"Mary",
"phone":"(444) 444-4444"
}
]';
# Convert String To Powershell Array
$people_obj = ConvertFrom-Json -InputObject $people;
# Loop through them and get each value by key.
Foreach($person in $people_obj ) {
echo $person.name;
}
제휴하지 않습니다 StackOverflow