繁体   English   中英

具有或不具有代码块的组对象差异

[英]Group-Object diffencies with or without code block

下面的代码生成2个“相同”的Hashtables,但是在使用代码块分组的代码块中,我无法从密钥中获取项目。

$HashTableWithoutBlock = 
    Get-WmiObject Win32_Service | Group-Object State -AsHashTable
$HashTableWithBlock = 
    Get-WmiObject Win32_Service | Group-Object {$_.State} -AsHashTable

Write-Host "Search result for HashTable without using code block : " -NoNewline
if($HashTableWithoutBlock["Stopped"] -eq $null)
{
    Write-Host "Failed"
}
else
{
    Write-Host "Success"
}

Write-Host "Search result for HashTable with code block : " -NoNewline
if($HashTableWithBlock["Stopped"] -eq $null)
{
    Write-Host "Failed"
}
else
{
    Write-Host "Success"
} 

输出:

Search result for HashTable without using code block : Success
Search result for HashTable with code block : Failed

两个Hashtables有什么区别?

如何获取按代码块分组的第二个项目?

编辑:不仅仅是一个解决方法,我想知道是否有可能通过表查找检索我想要的项目,如果是,如何?

两个Hashtable之间的区别在于$HashTableWithBlock将其密钥包装在PSObject 问题是PowerShell通常在将PSObject传递给方法调用之前将其解PSObject ,因此即使你有正确的键,你仍然不能将它传递给索引器。 要解决此问题,您可以创建帮助程序C#方法,该方法将使用正确的对象调用indexer。 另一种方法是使用反射:

Add-Type -TypeDefinition @'
    public static class Helper {
        public static object IndexHashtableByPSObject(System.Collections.IDictionary table,object[] key) {
            return table[key[0]];
        }
    }
'@
$HashTableWithBlock = Get-WmiObject Win32_Service | Group-Object {$_.State} -AsHashTable
$Key=$HashTableWithBlock.Keys-eq'Stopped'
#Helper method
[Helper]::IndexHashtableByPSObject($HashTableWithBlock,$Key)
#Reflection
[Collections.IDictionary].InvokeMember('','GetProperty',$null,$HashTableWithBlock,$Key)

其他海报是正确的,问题是密钥存储为PSObject但有一个内置的解决方案:使用-AsString开关和-AsHashTable 这将强制将密钥存储为字符串。 您可以在这里查看代码

我在GitHub上为这个bug打开了一个问题

这是我发现的一种解决方法,实际上并不是很好:

$HashTableWithBlock = 
    Get-WmiObject Win32_Service | ForEach-Object -Process {
        $_ | Add-Member -NotePropertyName _StateProp -NotePropertyValue $_.State -Force -Passthru
    } |
    Group-Object -Proerty _StateProp -AsHashTable

我的意思是我想,一旦你做了ForEach-Object你几乎可以自己构建一个哈希表吗?

请注意,有趣的是,如果您在ScriptProperty上进行分组,这将无效 我还没弄清楚原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM