powershell - 无法将对象转换为哈希表

标签 powershell

我有一个如下的哈希表:

$hashtable = @{
    "fruit" = "apple"
    "vegetable" = "carrot"
    "foo" = "bar"
    "test01" = "test"
    "test02" = "test"
    "test03" = "test"
    "test04" = "test"
}

现在我想删除像“测试”这样的条目并创建一个 new 哈希表:

[hashtable]$newHashTable = $hashtable.GetEnumerator() | `
Where-Object {$_.Name -notlike "test*"}

这会返回错误:无法将“System.Object[]”类型的“System.Object[]”值转换为“System.Collections.Hashtable”类型。

如何从过滤后的输出创建新的哈希表?

最佳答案

可能有更聪明的方法可以做到这一点,但以下方法可行:

$newhashtable = @{}
$hashtable.GetEnumerator() | Where-Object {$_.Name -notlike "test*"} | ForEach-Object { $newhashtable[$_.name] = $_.value }

您可以看到 $newhashtable 被保存为 Hastable:

PS> $newhashtable.gettype()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object

关于powershell - 无法将对象转换为哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55120179/

相关文章:

azure - 在命令行中使用参数运行PowerShell脚本(函数)

azure - 无法在azure devops管道中执行命令jq命令

powershell - Powershell将对象数组转换为PSCustomObject

azure - Powershell + Azure 应用服务 + Azure 容器注册表

Powershell 导入-CSV : either reorder columns with no headers or export-CSV with no header

powershell - 为什么 Write-Host "$PSCommandPath"没有输出我当前的路径?

sql - 使用 PowerShell 在 SQL Server 配置管理器中启用 TCP/IP

powershell - Powershell文件长度异常问题

powershell - 如何使用powershell下载文件?

powershell - 在Powershell中进行类型转换?奇怪的语法?