PowerShell – pass ordered hashtable to function
•
Java
How do I pass an ordered hash table to a function?
The following error was thrown: "ordered attributes can only be specified on Hash text nodes."
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 do 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 use it at present is not to specify 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
Solution
Use full type name:
function Do-Stuff {
param(
[System.Collections.Specialized.OrderedDictionary]$OrderedHashtable
)
$OrderedHashtable
}
To support regular hash tables and ordered dictionaries, you must use a separate parameter set: use the [system. Collections. Idictionary] interface, such as suggested by Briant
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
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
