PSCustomObject zu Hashtable
-
03-10-2019 - |
Frage
Was ist der einfachste Weg, um eine PSCustomObject
zu einem Hashtable
zu konvertieren? Es zeigt nur, wie man mit dem Splat-Operator, geschweiften Klammern und scheinbar Schlüsselwertepaar sein. Als ich nach Guss versuchen, es [Hashtable]
es nicht funktioniert. Ich habe auch versucht, .toString()
und die zugeordnete Variable sagt seine String, sondern zeigt nichts - alle Ideen
Lösung
sollte nicht zu hart sein. So etwas sollte es tun:
# 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 }
Andere Tipps
Keith hat Ihnen bereits die Antwort, das ist nur eine andere Art und Weise das gleiche zu tun, mit einem Einzeiler:
$psobject.psobject.properties | foreach -begin {$h=@{}} -process {$h."$($_.Name)" = $_.Value} -end {$h}
Hier ist eine Version, die Arbeiten mit verschachtelten Hashtables / Arrays als auch (was nützlich ist, wenn Sie versuchen, dies mit DSC Configuration zu tun):
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
}
}
}
Dies funktioniert für PSCustomObjects von ConvertFrom_Json erstellt.
Function ConvertConvertFrom-JsonPSCustomObjectToHash($obj)
{
$hash = @{}
$obj | Get-Member -MemberType Properties | SELECT -exp "Name" | % {
$hash[$_] = ($obj | SELECT -exp $_)
}
$hash
}
Disclaimer: Ich kaum Powershell verstehen, so ist dies wahrscheinlich nicht so sauber, wie es sein könnte. Aber es funktioniert (für eine Ebene nur).
Mein 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
}
}