尝试在函数中填充数组时没有结果

我正在试图使用一个函数来填充一个数组与计算机名称传递到另一个脚本的一部分。 我正在ping一个OU中的所有计算机名称,当它回到线上时,我想将其添加到数组中。 但是,每当我运行该function,它根本就没有计算机名称。

如果我手工完成这个function,它可以正常工作。 这里是代码:

Function Return-OnlinePCsInOU { [cmdletbinding()] param([Parameter(Mandatory=$true)] [String]$OU ) $computers = @() $machines = (Get-AdComputer -SearchBase $OU -Filter *).name $machines | Foreach { If (Test-Connection -ComputerName $_ -Count 1 -Quiet) { $computers += $_ } } } 

运行此函数不会填充数组。

所以,通过这个,我给出了OU中所有的计算机名称:

 $machines = (Get-AdComputer -SearchBase $OU -Filter *).name 

运行这一块获取在线机器和填充数组没有问题:

 $machines | Foreach { If (Test-Connection -ComputerName $_ -Count 1 -Quiet) { $computers += $_ } } PS C:\> $computers 71832 72098 83547 77437 77216 83427 81276 73293 71754 81308 67332 71765 

我希望这是我的愚蠢,但我不明白为什么它不会按我希望的方式工作。 任何帮助将是伟大的!

谢谢,德鲁

$computers$machines的范围都局限于函数Return-OnlinePCsInOu 。 当函数退出时,它们不在范围内。 你的函数也没有输出,所以没有任何东西是“返回”。 在shell / ISE中直接运行命令时,variables位于当前会话的范围内,您可以使用它们。

你可以通过添加一些简单的输出来看这个:

 Function Return-OnlinePCsInOU { [cmdletbinding()] param([Parameter(Mandatory=$true)] [String] $OU) $computers = @() $machines = (Get-AdComputer -SearchBase $OU -Filter *).name "Found: $machines" # writes search results $machines | Foreach { If (Test-Connection -ComputerName $_ -Count 1 -Quiet) { "Pinged $_" # writes when ping works $computers += $_ } } } Return-OnlinePCsInOU $computers # no output $machines # no output 

由于除了构build数组之外,您不需要使用variables$computer$machine ,所以我会跳过使用它们。 该函数可以直接生成所需的输出,您可以将其收集在一个variables中。

 Function Return-OnlinePCsInOU { [cmdletbinding()] param([Parameter(Mandatory=$true)] [String] $OU) Get-AdComputer -SearchBase $OU -Filter * | Foreach { If (Test-Connection -ComputerName $_.Name -Count 1 -Quiet) { $_.Name } } } # Scope is outside function, collect the output here. $onlineComputers = Return-OnlinePCsInOU 'DC=example,DC=org'