PowerShell 中的意外数据类型行为

问题描述 投票:0回答:1

我对 Powershell 还比较陌生。 我尝试将 Foreach 与 Switch 和数据类型检查结合起来。

$collection = @{A = 1; B="abc"; C = 33; D = "44" }

foreach($key in $collection.Keys){
`your text`switch ( ($collection.$key).GetType() ){
``your text``{ $_ -eq [int32]} {Write-Output "It's an integer"; break}
``your text``{ $_ -eq [string]} {Write-Output "It's a string"; break}}
}

#Second attempt

foreach($key in $collection.Keys){
`your text`switch ($collection.$key.GetType()){
``your text``{$PSItem -eq [System.Int32]} {Write-Host "It's an integer"; break}
``your text``{$PSItem -eq [System.String]} {Write-Host "It's a string"; break}
        }
}

我得到的结果是:

它是一个整数 这是一个字符串 这是一个字符串 这是一个整数

我尝试过转换数据类型或使用 -is 比较

我不想使用 if 但了解我缺少什么。

有人可以告诉我为什么吗?

powershell for-loop switch-statement
1个回答
0
投票

$Collection
[Hashtable]

哈希表不保留键的顺序。

您需要使用

[Ordered]
字典:

$collection = [ordered]@{A = 1; B = "abc"; C = 33; D = "44"; W = 9.9 }

foreach ($key in $collection.Keys) {
    write-host "Key '$key' is " -NoNewline
    switch ( $Collection.$key ) {
        { $_ -is [Int32] } { write-host "an [integer]"; break }
        { $_ -is [string] } { write-host "a [string]"; break }
        default { Write-Host "not a [String] or [Int]. It's a [$($_.gettype())]" }
    }
}

结果:

Key 'A' is an [integer]
Key 'B' is a [string]
Key 'C' is an [integer]
Key 'D' is a [string]
Key 'W' is not a [String] or [Int]. It's a [double]

如您所见,有序字典基本上是“保留键顺序的哈希表”

© www.soinside.com 2019 - 2024. All rights reserved.