Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell中的可枚举项与管道_Powershell_Powershell 3.0 - Fatal编程技术网

Powershell中的可枚举项与管道

Powershell中的可枚举项与管道,powershell,powershell-3.0,Powershell,Powershell 3.0,我很困惑。我不明白为什么Powershell中的foreach与C#的行为如此不同 此简单代码不产生任何输出: @{a=1; b=2} | %{ $_.key } 我在Linqpad中使用C#做的一个近似值给出了我期望的输出: var ht = new Hashtable(); ht["a"] = 1; ht["b"] = 2; foreach (DictionaryEntry kvp in ht) { kvp.Key.Dump(); } // output a b 如果我枚举

我很困惑。我不明白为什么Powershell中的foreach与C#的行为如此不同

此简单代码不产生任何输出:

@{a=1; b=2} | %{ $_.key }
我在Linqpad中使用C#做的一个近似值给出了我期望的输出:

var ht = new Hashtable();
ht["a"] = 1;
ht["b"] = 2;

foreach (DictionaryEntry kvp in ht)
{
    kvp.Key.Dump();
}

// output

a
b
如果我枚举哈希表的键成员,我可以做我需要的事情。但是我不明白为什么枚举哈希表本身不返回键值对。实际上,它似乎返回了对象本身:

>     @{a=1; b=2} | %{ $_.gettype() }

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object

Powershell在这里做什么?

Powershell管道将“展开”数组和集合(一级),但不会展开哈希表。如果要枚举PowerShell中哈希表的键值对,请调用.getenumerator()方法:


耶,这就是我需要的,谢谢!顺便问一下,你怎么知道的?有没有解释展开的文件?我甚至没有想过在我的搜索中使用这个关键词,虽然现在我知道了,我看到了很多点击率。我不记得我第一次从哪里学到这个,或者是通过发现,但你可以很容易地自己验证它。构建一个2D数组,并通过管道将其发送到foreach对象。每个对象都将是第二级数组中的一个。实际上,如果要防止管道展开数组,则需要使用逗号前缀传递数组,如:,@(1,2,3),然后将整个数组实例作为单个管道对象传递,而不是在内容上迭代。(就我个人而言,我觉得展开非常烦人,似乎总是与我想要的相反,但谁知道呢,也许我只是没有充分利用这一功能)
$ht = @{a=1;b=2}
$ht.GetEnumerator()



Name                           Value                                                             
----                           -----                                                             
a                              1                                                                 
b                              2