PSCustomObject a Hashtable
-
03-10-2019 - |
Pregunta
¿Cuál es la forma más fácil de convertir un PSCustomObject
a un Hashtable
? Se muestra como uno con el operador splat, las llaves y lo que parecen ser los pares de valores clave. Cuando trato de echarlo a [Hashtable]
no funciona. También probé .toString()
y la variable asignada dice que es una cadena, pero no muestra nada - cualquier idea
Solución
no debe ser demasiado difícil. Algo como esto debe hacer el truco:
# 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 }
Otros consejos
Keith ya le dio la respuesta, esto es sólo otra forma de hacer lo mismo con una sola línea:
$psobject.psobject.properties | foreach -begin {$h=@{}} -process {$h."$($_.Name)" = $_.Value} -end {$h}
Aquí hay una versión que funciona con anidadas tablas hash / matrices también (lo cual es útil si usted está tratando de hacer esto con 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
}
}
}
Esto funciona para PSCustomObjects creados por ConvertFrom_Json.
Function ConvertConvertFrom-JsonPSCustomObjectToHash($obj)
{
$hash = @{}
$obj | Get-Member -MemberType Properties | SELECT -exp "Name" | % {
$hash[$_] = ($obj | SELECT -exp $_)
}
$hash
}
exención de responsabilidad: yo apenas entiendo PowerShell así que esto no es probablemente tan limpio como podría ser. Pero funciona (para un solo nivel).
Mi código:
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
}
}