问题
I am trying to execute a script in PowerShell 2.0 that will check the trust relationship between the computer and domain controller for all computers in Active Directory.
I got the code from this website: https://adamtheautomator.com/trust-relationship-between-this-workstation-and-the-primary-domain-failed/
Here is the code:
$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
})
I am getting the error
"Method invocation failed because [System.Object[]] doesn't contain a method named 'foreach'.
Can someone explain why I am getting this error? Is my syntax wrong for this version of PowerShell? Any help would be greatly appreciated.
Please click below for image with details.
回答1:
the .Where()
and .ForEach()
collection methods were added in powershell v4, so you cannot use them in PoSh v2. [grin]
instead, use the foreach () {}
standard loop OR the ForEach-Object
pipeline cmdlet. generally speaking, the 1st is faster and somewhat easier to debug, while the 2nd uses less RAM and is easier to use at the command line.
for more info, please see the MSDocs here ...
about_Methods - PowerShell | Microsoft Docs
— 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.
来源:https://stackoverflow.com/questions/61738206/method-invocation-foreach-failed-system-object-doesnt-contain-a-method-named