简体   繁体   English

Powershell中对foreach的不同输入

[英]Different inputs for foreach in Powershell

I've got two beginner's questions regarding data types in Powershell. 关于Powershell中的数据类型,我有两个初学者的问题。

  1. why does these two commands differ in results? 为什么这两个命令的结果不同?

     PS > $test = {"a", "b", "c"} PS > foreach ($item in $test) { $item | Out-Host } "a", "b", "c" PS > $test = "a", "b", "c" PS > foreach ($item in $test) { $item | Out-Host } a b c 
  2. One command returns data, which - when formatted as list - looks like the following: 一个命令返回数据,当格式化为列表时,它们如下所示:

     Changes : {Change instance 10406282 ChangeType: Edit (...) , Change instance 25906333 ChangeType: Edit (...) } 

    It looks like this is some kind of a list of items. 看起来这是某种物品清单。 How can I foreach through them? 我怎样才能通过它们进行foreach

First question If you do following: $test = {"a", "b", "c"} $test.GetType() 第一个问题如果你这样做:$ test = {“a”,“b”,“c”} $ test.GetType()

$test = "a", "b", "c"
$test.GetType()

You will notice that the first object is ScriptBlock the second one is an array 您会注意到第一个对象是ScriptBlock ,第二个对象是数组

Second question 第二个问题

Assign result to an object and simple iterate as you do above. 将结果分配给对象,并像上面一样简单迭代。

Simple example: 简单的例子:

$result = (Get-TfsItemHistory $/<projectName> -all -user $name -Recurse -server $tfs)
$result | foreach {$item = $_; Write-Host $item; Write-Host $item.ChangeType;}

{...} creates a scriptblock, you might think that the loop runs 3 times but it's not (one iteration only), it just returns the content of the script block. {...}创建一个scriptblock,你可能认为循环运行了3次但不是(仅一次迭代),它只返回脚本块的内容。

Items seperated by a comma creates a collection of items (array). 由逗号分隔的项目会创建项目集合(数组)。 When you loop over a collection you iterate over each item int he collection 循环遍历集合时,将遍历集合中的每个项目

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

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