带或不带代码块的组对象差异 [英] Group-Object diffencies with or without code block

查看:53
本文介绍了带或不带代码块的组对象差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码生成了 2 个相同"的哈希表,但是在使用代码块分组的一个哈希表上,我无法从键中获取项目.

The code below produce 2 "identical" Hashtables, however on the one that was grouped using a code block I can't get items from the key.

$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

这两个Hashtable有什么区别?

What is the difference between the two Hashtables ?

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

How to get Items on second one that was grouped by code block ?

不仅仅是一种解决方法,我想知道是否可以通过表查找来检索我想要的项目,如果是,如何?

EDIT : More than a workaround, I'd like to know if it is possible to retrieve the Item I want with a table lookup, and if yes, how ?

推荐答案

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

The difference between two Hashtables is that $HashTableWithBlock have its key wrapped in PSObject. Problem is that PowerShell normally unwrap PSObject before pass it to the method call, so even if you have right key, you still can not just pass it to indexer. To workaround this you can create helper C# method what would call indexer with right object. Another way is to use reflection:

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)

这篇关于带或不带代码块的组对象差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆