当 运行 on PS v4 时,Powershell v2.0 Foreach 循环失败

Powershell v2.0 Foreach loop failing when run on PS v4

您好,PS v4(运行 来自 2012 服务器)对用 V2 编写的 Foreach 循环的反应方式有何不同?

我有一个在 v2 中运行但在 v4 中产生错误的简单脚本:

$Serverlist = Import-CSV "D:\PendingReboot\AllADServers.csv"
    Foreach ($Computer.Name in $Serverlist)
    {      
          $ADComputer = $Computer.Name
          $ADOwner = $Computer.Description
          If (!($Computer.Description))
          {$ADOwner = "Unassigned"}
          $ADOU = $AD | select DistinguishedName 
          "$ADComputer $ADOwner"
    }

Server1 Team1
Server2 Team2
etc. etc.

V4 中的错误是:

At D:\PendingReboot\Test.ps1:2 char:23
+     Foreach ($Computer.Name in $Serverlist)
+                       ~
Missing 'in' after variable in foreach loop.
At D:\PendingReboot\Test.ps1:2 char:43
+     Foreach ($Computer.Name in $Serverlist)
+                                           ~
Unexpected token ')' in expression or statement.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingInInForeach

PetSerAl 的评论是正确的。您应该使用 foreach ($Computer in $ServerList)。至于为什么它适用于 PowerShell v2 而不是 v4,我只能假设他们纠正了行为,因为它应该在 v2 中失败。

基本上,您在该部分的 .Name 什么都不做,事实证明您仍然需要在循环的第一行指定 .Name

本质上,这是早期版本中未发现的语法错误。