powershell – 将Ordered Hashtable传递给函数

前端之家收集整理的这篇文章主要介绍了powershell – 将Ordered Hashtable传递给函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何将有序哈希表传递给函数

以下引发错误“只能在散列文字节点上指定有序属性.”

function doStuff {
    Param (
        [ordered]$theOrderedHashtable
    )
    $theOrderedHashtable
}

$datFileWithMinSizes  = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847"  }


doStuff -theOrderedHashtable $datFileWithMinSizes

以下不保持正确的顺序:

function doStuff {
    Param (
        [Hashtable]$theOrderedHashtable = [ordered]@{}
    )
    $theOrderedHashtable
}

$datFileWithMinSizes  = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847"  }


doStuff -theOrderedHashtable $datFileWithMinSizes

我目前能够使用它的唯一方法是不指定类型如下,但我想指定类型:

function doStuff {
    Param (
        $theOrderedHashtable
    )
    $theOrderedHashtable
}

$datFileWithMinSizes  = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847"  }


doStuff -theOrderedHashtable $datFileWithMinSizes

解决方法

使用完整类型名称
function Do-Stuff {
    param(
        [System.Collections.Specialized.OrderedDictionary]$OrderedHashtable
    )
    $OrderedHashtable
}

支持常规哈希表和有序词典,您必须使用单独的参数集:使用[System.Collections.IDictionary]接口,如suggested by briantist

function Do-Stuff {
    [CmdletBinding(DefaultParameterSetName='Ordered')]
    param(
        [Parameter(Mandatory=$true,Position=0,ParameterSetName='Ordered')]
        [System.Collections.Specialized.OrderedDictionary]$OrderedHashtable,[Parameter(Mandatory=$true,ParameterSetName='Hashtable')]
        [hashtable]$Hashtable
    )
    if($PSCmdlet.ParameterSetName -eq 'Hashtable'){
        $OrderedHashtable = $Hashtable
    }
    $OrderedHashtable
}

猜你在找的Java相关文章