首页 > 解决方案 > PowerShell 2.0,Get-ADComputer 脚本问题(无输出)

问题描述

我正在尝试使用下面的脚本来测试 AD 中每台计算机与域控制器的信任关系。我正在使用 powershell 2.0。当我测试脚本时,我没有得到任何输出。它基于一个有效的 powershell 4.0 脚本。

    $localCredential = Get-Credential

ForEach ($Name in Get-AdComputer -Filter *){

   $output = { $Name = $_.Name }

   if (-not (Test-Connection $Name $_.Name -Quiet -Count 1)) { $output.Status = 'Offline'
   } else {
       $trustStatus = Invoke-Command $Name $_.Name -ScriptBlock { Test-ComputerSecureChannel } -Credential $localCredential
       $output.Status = $trustStatus
   }

   [pscustomobject]$output

}

下面是我尝试转换的 powershell 4.0 脚本,因为 .ForEach 语法在 Powershell 2.0 中无效。

来源:https ://adamtheautomator.com/trust-relationship-between-this-workstation-and-the-primary-domain-failed/

这是我尝试转换的工作脚本:

    $localCredential = Get-Credential

@(Get-AdComputer -Filter *).foreach({

   $output = @{ ComputerName = $_.Name }

   if (-not (Test-Connection -ComputerName $_.Name -Quiet -Count 1)) { $output.Status = 'Offline'
   } else {
       $trustStatus = Invoke-Command -ComputerName $_.Name -ScriptBlock { Test-ComputerSecureChannel } -Credential $localCredential
       $output.Status = $trustStatus
   }

   [pscustomobject]$output

})

有谁知道为什么我没有得到输出?我发布的第一个脚本有明显问题吗?任何帮助将不胜感激。

非常感谢,

戴夫

标签: powershellactive-directorypowershell-2.0

解决方案


foreach()语句中您声明了迭代器变量$Name,但在循环体内您也不一致地使用$_

您还使用[pscustomobject]@{}PowerShell 3.0 中引入的特殊对象分配语法 - 您需要New-Object psobject -Property在 2.0 版中使用。

最后,您的$output变量需要是字典而不是脚本块(注意@前面的{ Name = ... })。

要解决这一切:

ForEach ($Computer in Get-AdComputer -Filter *){

   $output = @{ Name = $Computer.Name }

   if (-not (Test-Connection $Computer.Name -Quiet -Count 1)) {
       $output.Status = 'Offline'
   } else {
       $trustStatus = Invoke-Command -ComputerName $Computer.Name -ScriptBlock { Test-ComputerSecureChannel } -Credential $localCredential
       $output.Status = $trustStatus
   }

   New-Object psobject -Property $output
}

推荐阅读