如果 - foreach中的其他内容不会返回我认为应该返回的内容

时间:2017-05-09 20:38:16

标签: arrays powershell if-statement foreach

我有一系列需要循环的服务器,并且只将属性分配给特定的服务器(这将在后面的脚本中发生)。

这是数组:

$test = @('test_dc','test_fp','test_ts','test_ap')

在数组中,我有一个域控制器,文件/打印,终端服务器和应用程序服务器(按此顺序)。

应该获取该属性的唯一服务器是fp,ts和ap服务器。

这是我到目前为止所尝试的内容:

foreach ($item in $test) {
  Write-Host $item "`n"
  Write-Host "Start IF here `n"
  if ($item.Name -like '*fp*') {
    Write-Host "Found $item"
  } else {
    Write-Host "ELSE `n"
    Write-Host '-=-=-=-=-'
  }
}

以下是该输出:

PS C:\Users\me\Desktop> .\scratch.ps1

test_dc

Start IF here

ELSE

-=-=-=-=-

test_fp

Start IF here

ELSE

-=-=-=-=-

test_ts

Start IF here

ELSE

-=-=-=-=-

test_ap

Start IF here

ELSE

-=-=-=-=- 
PS C:\Users\me\Desktop>

根据我认为工作的方式,我应该看到:

...
test_fp

Found test_fp
...

我也试过这个:

if ($test -contains '*fp') {
  Write-Host "Found $_"
} else {
  Write-Host 'end'
}

我得到一个空行。

1 个答案:

答案 0 :(得分:3)

您正在看到正在向主机写入额外信息,因为您对每个项目都有无限期写入,无论它是否匹配。由于您还包含else语句,因此您将看到针对不匹配项目编写的额外内容。您的foreach循环还指定了对象的name属性,而$test数组仅包含字符串。

以下是我更新的内容,以限制只在循环中写入主机名,如果它匹配*fp*,否则写下你的分隔符:

$test = @('test_dc','test_fp','test_ts','test_ap')
foreach ($item in $test) {
  if ($item -like '*fp*') {
    Write-Host "Found $item"
  } else {
    Write-Host '-=-=-=-=-'
  }
}

运行它会输出:

-=-=-=-=-
Found test_fp
-=-=-=-=-
-=-=-=-=-