반응형
PSCustomObject에서 Hashtable로
a PSCustomObject
를 a 로 변환하는 가장 쉬운 방법은 무엇입니까 Hashtable
? splat 연산자, 중괄호 및 키 값 쌍으로 보이는 항목이있는 것처럼 표시됩니다. 캐스팅하려고하면 [Hashtable]
작동하지 않습니다. 나는 또한 시도 .toString()
하고 할당 된 변수는 문자열이라고 말하지만 아무것도 표시하지 않습니다.
너무 어렵지 않아야합니다. 다음과 같은 것이 트릭을 수행해야합니다.
# Create a PSCustomObject (ironically using a hashtable)
$ht1 = @{ A = 'a'; B = 'b'; DateTime = Get-Date }
$theObject = new-object psobject -Property $ht1
# Convert the PSCustomObject back to a hashtable
$ht2 = @{}
$theObject.psobject.properties | Foreach { $ht2[$_.Name] = $_.Value }
Keith는 이미 답을주었습니다. 이것은 한 줄짜리로 동일한 작업을 수행하는 또 다른 방법입니다.
$psobject.psobject.properties | foreach -begin {$h=@{}} -process {$h."$($_.Name)" = $_.Value} -end {$h}
다음은 중첩 된 해시 테이블 / 배열에서도 작동하는 버전입니다 (DSC ConfigurationData로이 작업을 수행하려는 경우 유용합니다).
function ConvertPSObjectToHashtable
{
param (
[Parameter(ValueFromPipeline)]
$InputObject
)
process
{
if ($null -eq $InputObject) { return $null }
if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string])
{
$collection = @(
foreach ($object in $InputObject) { ConvertPSObjectToHashtable $object }
)
Write-Output -NoEnumerate $collection
}
elseif ($InputObject -is [psobject])
{
$hash = @{}
foreach ($property in $InputObject.PSObject.Properties)
{
$hash[$property.Name] = ConvertPSObjectToHashtable $property.Value
}
$hash
}
else
{
$InputObject
}
}
}
이것은 ConvertFrom_Json이 만든 PSCustomObjects에서 작동합니다.
Function ConvertConvertFrom-JsonPSCustomObjectToHash($obj)
{
$hash = @{}
$obj | Get-Member -MemberType Properties | SELECT -exp "Name" | % {
$hash[$_] = ($obj | SELECT -exp $_)
}
$hash
}
Disclaimer: I barely understand PowerShell so this is probably not as clean as it could be. But it works (for one level only).
My code:
function PSCustomObjectConvertToHashtable() {
param(
[Parameter(ValueFromPipeline)]
$object
)
if ( $object -eq $null ) { return $null }
if ( $object -is [psobject] ) {
$result = @{}
$items = $object | Get-Member -MemberType NoteProperty
foreach( $item in $items ) {
$key = $item.Name
$value = PSCustomObjectConvertToHashtable -object $object.$key
$result.Add($key, $value)
}
return $result
} elseif ($object -is [array]) {
$result = [object[]]::new($object.Count)
for ($i = 0; $i -lt $object.Count; $i++) {
$result[$i] = (PSCustomObjectConvertToHashtable -object $object[$i])
}
return ,$result
} else {
return $object
}
}
참고URL : https://stackoverflow.com/questions/3740128/pscustomobject-to-hashtable
반응형
'IT TIP' 카테고리의 다른 글
이니셜 라이저 오류의 예외 (0) | 2020.11.23 |
---|---|
Visual Studio 2010은 "다시 작성"을 수동으로 선택하지 않는 한 변경된 코드를 다시 작성하지 않습니다. (0) | 2020.11.23 |
비트 시프트 (왼쪽 또는 오른쪽)의 기능과 용도는 무엇입니까? (0) | 2020.11.23 |
Bash에서 가능한 상대 경로 확장 (0) | 2020.11.23 |
setuptools에 정적 파일을 포함하는 방법-Python 패키지 (0) | 2020.11.23 |