powershell PSCustomObject到Hashtable

1u4esq0p  于 2023-04-21  发布在  Shell
关注(0)|答案(8)|浏览(151)

PSCustomObject转换为Hashtable的最简单方法是什么?它的显示就像一个splat运算符,花括号和似乎是键值对的东西。当我试图将它转换为[Hashtable]时,它不起作用。我还尝试了.toString(),赋值的变量说它是一个字符串,但什么也不显示-有什么想法吗?

jjjwad0x

jjjwad0x1#

不会太难的。像这样的东西应该可以:

# 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 }
oewdyzsn

oewdyzsn2#

基思已经给了你答案,这只是用一行程序做同样事情的另一种方式:

$psobject.psobject.properties | foreach -begin {$h=@{}} -process {$h."$($_.Name)" = $_.Value} -end {$h}
6xfqseft

6xfqseft3#

这里有一个版本,也可以使用嵌套的哈希表/数组(如果你试图使用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] = (Convert-PSObjectToHashtable $property.Value).PSObject.BaseObject
            }

            $hash
        }
        else
        {
            $InputObject
        }
    }
}
oxosxuxt

oxosxuxt4#

我非常懒惰的方法,由PowerShell 6中的一个新功能启用:

$myhashtable = $mypscustomobject | ConvertTo-Json | ConvertFrom-Json -AsHashTable
8tntrjer

8tntrjer5#

这适用于由ConvertFrom_Json创建的PSCustomObjects。

Function ConvertConvertFrom-JsonPSCustomObjectToHash($obj)
{
    $hash = @{}
     $obj | Get-Member -MemberType Properties | SELECT -exp "Name" | % {
                $hash[$_] = ($obj | SELECT -exp $_)
      }
      $hash
}

免责声明:我几乎不懂PowerShell,所以这可能不像它可能的那样干净。但它可以工作(只适用于一个级别)。

3mpgtkmj

3mpgtkmj6#

我的代码:

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
    }
}
wpx232ag

wpx232ag7#

对于简单的[PSCustomObject]到[Hashtable]转换,Keith's Answer效果最好。
但是如果你需要更多的选项,你可以使用

function ConvertTo-Hashtable {
    <#
    .Synopsis
        Converts an object to a hashtable
    .DESCRIPTION
        PowerShell v4 seems to have trouble casting some objects to Hashtable.
        This function is a workaround to convert PS Objects to [Hashtable]
    .LINK
        https://github.com/alainQtec/.files/blob/main/src/scripts/Converters/ConvertTo-Hashtable.ps1
    .NOTES
        Base ref: https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/turning-objects-into-hash-tables-2
    #>
    PARAM(
        # The object to convert to a hashtable
        [Parameter(ValueFromPipeline = $true, Mandatory = $true)]
        $InputObject,

        # Forces the values to be strings and converts them by running them through Out-String
        [switch]$AsString,

        # If set, empty properties are Included
        [switch]$AllowNulls,

        # Make each hashtable to have it's own set of properties, otherwise,
        # (default) each InputObject is normalized to the properties on the first object in the pipeline
        [switch]$DontNormalize
    )
    BEGIN {
        $headers = @()
    }
    PROCESS {
        if (!$headers -or $DontNormalize) {
            $headers = $InputObject | Get-Member -type Properties | Select-Object -expand name
        }
        $OutputHash = @{}
        if ($AsString) {
            foreach ($col in $headers) {
                if ($AllowNulls -or ($InputObject.$col -is [bool] -or ($InputObject.$col))) {
                    $OutputHash.$col = $InputObject.$col | Out-String -Width 9999 | ForEach-Object { $_.Trim() }
                }
            }
        } else {
            foreach ($col in $headers) {
                if ($AllowNulls -or ($InputObject.$col -is [bool] -or ($InputObject.$col))) {
                    $OutputHash.$col = $InputObject.$col
                }
            }
        }
    }
    END {
        return $OutputHash
    }
}

也许这是矫枉过正,但我希望它帮助

ux6nzvsh

ux6nzvsh8#

今天,将PSCustomObject转换为Hashtable的“最简单方法”是:

$custom_obj | ConvertTo-HashtableFromPsCustomObject

[hashtable]$custom_obj

相反,您可以使用以下命令将Hashtable转换为PSCustomObject:

[PSCustomObject]$hash_table

唯一的障碍是,这些漂亮的选项可能无法在旧版本的PS

相关问题