PSCustomObject a Hashtable
-
03-10-2019 - |
Domanda
Qual è il modo più semplice per convertire un PSCustomObject
ad un Hashtable
? Esso mostra come una con l'operatore splat, graffe e che sembrano essere coppie di valori chiave. Quando provo a lanciarlo a [Hashtable]
non funziona. Ho anche provato .toString()
e la variabile assegnata dice la sua una stringa ma visualizza nulla? - tutte le idee
Soluzione
non dovrebbe essere troppo difficile. Qualcosa del genere dovrebbe fare il trucco:
# 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 }
Altri suggerimenti
Keith già ti ha dato la risposta, questo è solo un altro modo di fare la stessa cosa con una battuta:
$psobject.psobject.properties | foreach -begin {$h=@{}} -process {$h."$($_.Name)" = $_.Value} -end {$h}
Ecco una versione che funziona con hashtables annidati / array come ben (che è utile se si sta cercando di fare questo con DSC Dati di configurazione):
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
}
}
}
Questo funziona per PSCustomObjects create da ConvertFrom_Json.
Function ConvertConvertFrom-JsonPSCustomObjectToHash($obj)
{
$hash = @{}
$obj | Get-Member -MemberType Properties | SELECT -exp "Name" | % {
$hash[$_] = ($obj | SELECT -exp $_)
}
$hash
}
Disclaimer: io a malapena capire PowerShell quindi questo probabilmente non è pulita come avrebbe potuto essere. Ma funziona (per un solo livello).
Il mio codice:
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
}
}