0

我有两个关于 Powershell 中数据类型的初学者问题。

  1. 为什么这两个命令的结果不同?

    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. 一个命令返回数据,当格式化为列表时,数据如下所示:

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

    看起来这是某种项目列表。我怎样才能foreach通过它们?

4

2 回答 2

2

第一个问题 如果您执行以下操作: $test = {"a", "b", "c"} $test.GetType()

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

你会注意到第一个对象是ScriptBlock第二个对象是一个数组

第二个问题

将结果分配给一个对象并像上面那样简单地迭代。

简单的例子:

$result = (Get-TfsItemHistory $/<projectName> -all -user $name -Recurse -server $tfs)
$result | foreach {$item = $_; Write-Host $item; Write-Host $item.ChangeType;}
于 2013-06-24T10:53:27.980 回答
0

{...} 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.

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

于 2013-06-24T11:07:51.880 回答