试试这个:
$computername = Read-Host 'Enter Computer Name'
$online = Test-Connection -Computername $computername -BufferSize 16 -Count 1 -Quiet
IF ($online -eq $true) {
Write-Host "Device is online"
Test-Connection $computername -count 1 | select @{Name="Computername";Expression={$_.Address}},Ipv4Address
try {
[PSObject[]]$systemEnclosures = Get-WmiObject win32_SystemEnclosure -computername $computername -ErrorAction Stop
Write-Host "Found $($systemEnclosures.Count) System Enclosures"
$systemEnclosures | select serialnumber
[PSObject[]]$NetworkAdapterConfiguration = Get-wmiobject -class "Win32_NetworkAdapterConfiguration" -computername $computername -ErrorAction Stop
Write-Host "Found $($NetworkAdapterConfiguration.Count) Network Adapter Configurations"
$NetworkAdapterConfiguration = $NetworkAdapterConfiguration | Where{$_.IpEnabled}
Write-Host "Found $($NetworkAdapterConfiguration.Count) IP Enabled Network Adapter Configurations"
$NetworkAdapterConfiguration
} catch {
Write-Host "An Error Occurred"
Write-Host $_.ToString() #show exception info
}
} Else {
Write-Host "Device is offline"
}
注意:我并不是建议您将此代码保留在最终脚本中;只需使用它来了解幕后发生的事情。
每厘米;使用$true 而不是"true",好像两者都是真实的,使用错误的类型会导致对语言的错误理解/一些非常奇怪的错误,你发现像if($true -eq "false") {write-output "Well, this is unusual"} 这样的行会导致一些奇怪行为。
此外,您可能希望考虑将 Write-Host 替换为 Write-Output 以获取任何逻辑返回值,或将 Write-Verbose/Write-Debug 替换为任何信息/调查输出;然后使用适当的开关/首选项调用代码......但这与您的问题无关。 Write-Host Considered Harmful 了解更多信息。
更新
每个 cmets,您看到的问题是一个 错误 陷阱:https://github.com/PowerShell/PowerShell/issues/4552
如果这段代码输出的数据只是在控制台中显示,你可以通过显式调用Format-Table命令来避免这个问题:
$computername = Read-Host 'Enter Computer Name'
IF (Test-Connection -Computername $computername -BufferSize 16 -Count 1 -Quiet) {
Test-Connection $computername -count 1 | select @{Name="Computername";Expression={$_.Address}}, 'Ipv4Address' | Format-Table
Get-WmiObject win32_SystemEnclosure -computername $computername | select serialnumber | Format-Table
Get-wmiobject -class "Win32_NetworkAdapterConfiguration" -computername $computername | Where{$_.IpEnabled} | Format-Table
} Else {
Write-Host "Device is offline"
}
如果您需要输出到管道以供其他地方使用,一切都很好(即没有format-table 块);对象被正确写入管道;问题很简单,当涉及到一起显示所有结果时,第一个对象导致 PowerShell 创建列 ComputerName 和 Ipv4Address,并且 PowerShell 随后尝试显示以下对象的这些属性,尽管那些没有这样的对象特性。也就是说,可以通过将不同的对象类型放入自定义对象的不同属性中以便于参考来改进这一点。例如,
$computername = Read-Host 'Enter Computer Name'
If (Test-Connection -Computername $computername -BufferSize 16 -Count 1 -Quiet) {
(new-object -TypeName PSObject -Property @{
ConnectionTest = Test-Connection $computername -count 1 | select @{Name="Computername";Expression={$_.Address}}, 'Ipv4Address'
SystemEnclosures = Get-WmiObject win32_SystemEnclosure -computername $computername | select serialnumber
NetworkAdapterConfigs = Get-wmiobject -class "Win32_NetworkAdapterConfiguration" -computername $computername | Where{$_.IpEnabled}
})
} Else {
Write-Host "Device is offline"
}