How can I go about passing an ordered hashtable to a function?
The following throws an error:
The ordered attribute can be specified only on a hash literal node.
function doStuff {
Param (
[ordered]$theOrderedHashtable
)
$theOrderedHashtable
}
$datFileWithMinSizes = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847" }
doStuff -theOrderedHashtable $datFileWithMinSizes
The following does not maintain the correct order:
function doStuff {
Param (
[Hashtable]$theOrderedHashtable = [ordered]@{}
)
$theOrderedHashtable
}
$datFileWithMinSizes = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847" }
doStuff -theOrderedHashtable $datFileWithMinSizes
The only way I can currently get this to work is by not specifying the type as follows, but I want to specify the type:
function doStuff {
Param (
$theOrderedHashtable
)
$theOrderedHashtable
}
$datFileWithMinSizes = [ordered]@{"FileA.DAT" = "4"; "FileB.DAT" = "5"; "FileC.DAT" = "91" ; "FileD.DAT" = "847" }
doStuff -theOrderedHashtable $datFileWithMinSizes
Instead, you can use PowerShell splatting. To splat a parameter set, first create a hashtable containing key/value pairs of each parameter and parameter argument. Then, once you have the hashtable built, pass that set of parameters to the command using @<hashtable name> .
To display a hash table that is saved in a variable, type the variable name. By default, a hash tables is displayed as a table with one column for keys and one for values. Hash tables have Keys and Values properties. Use dot notation to display all of the keys or all of the values.
Generally, you think of a hashtable as a key/value pair, where you provide one key and get one value. PowerShell allows you to provide an array of keys to get multiple values. In this example, I use the same lookup hashtable from above and provide three different array styles to get the matches.
Use the full type name:
function Do-Stuff {
param(
[System.Collections.Specialized.OrderedDictionary]$OrderedHashtable
)
$OrderedHashtable
}
To support both regular hashtables and ordered dictionaries, you'll have to use separate parameter sets: use the [System.Collections.IDictionary]
interface, as 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,Position=0,ParameterSetName='Hashtable')]
[hashtable]$Hashtable
)
if($PSCmdlet.ParameterSetName -eq 'Hashtable'){
$OrderedHashtable = $Hashtable
}
$OrderedHashtable
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With