方法调用 .Foreach 失败,System.Object 不包含名为 'foreach' 的方法
Method Invocation .Foreach failed, System.Object doesn't contain a method named 'foreach'
我正在尝试在 PowerShell 2.0 中执行一个脚本,该脚本将检查 Active Directory 中所有计算机的计算机和域控制器之间的信任关系。
代码如下:
$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
})
我遇到错误
"Method invocation failed because [System.Object[]] doesn't contain a method named 'foreach'.
有人可以解释为什么我会收到此错误吗?此版本的 PowerShell 的语法是否错误?任何帮助将不胜感激。
请点击下面的图片查看详情。
powershell v4 中添加了.Where()
和.ForEach()
收集方法,因此您不能在PoSh v2 中使用它们。 [咧嘴一笑]
而是使用 foreach () {}
标准循环或 ForEach-Object
管道 cmdlet。一般来说,第一个更快并且更容易调试,而第二个使用更少的 RAM 并且更容易在命令行中使用。
有关详细信息,请参阅此处的 MSDocs ...
about_Methods - PowerShell |微软文档
— https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_methods?view=powershell-7
Beginning in PowerShell 4.0, collection filtering by using a method syntax is supported.
我正在尝试在 PowerShell 2.0 中执行一个脚本,该脚本将检查 Active Directory 中所有计算机的计算机和域控制器之间的信任关系。
代码如下:
$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
})
我遇到错误
"Method invocation failed because [System.Object[]] doesn't contain a method named 'foreach'.
有人可以解释为什么我会收到此错误吗?此版本的 PowerShell 的语法是否错误?任何帮助将不胜感激。
请点击下面的图片查看详情。
powershell v4 中添加了.Where()
和.ForEach()
收集方法,因此您不能在PoSh v2 中使用它们。 [咧嘴一笑]
而是使用 foreach () {}
标准循环或 ForEach-Object
管道 cmdlet。一般来说,第一个更快并且更容易调试,而第二个使用更少的 RAM 并且更容易在命令行中使用。
有关详细信息,请参阅此处的 MSDocs ...
about_Methods - PowerShell |微软文档
— https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_methods?view=powershell-7
Beginning in PowerShell 4.0, collection filtering by using a method syntax is supported.