我对 PowerShell 还是很陌生,所以为了更好地学习技巧,我正在开发一个 Powershell 函数来返回我们网络中计算机的一些基本概述信息。我已经得到了我正在寻找的所有东西,但我不知道如何显示WMI查询返回的数组的所有结果,例如硬盘或MAC 地址。
例如,现在我正在使用 WMI 查询“DHCPEnabled = TRUE”来检测活动的NIC并检索它们的 MAC 地址 - 但在笔记本电脑上,理论上查询可能会返回有线和无线 NIC。
然后,此命令的输出将显示我创建的自定义PSObject,但在生成的 PSObject 中,该属性MACAddress
将显示为空白。结果就在那里,我可以通过管道或Select-Object获得它们,但我不知道如何将它们保存为报告或以其他方式“美化”它们。
这是我现在拥有的工作函数,它假设返回的第一个结果是我唯一关心的结果。同样,在此示例中,这主要是对硬盘和 MAC 地址的关注,但我想了解其背后的概念以供将来参考。
Function Get-PCInfo
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[Alias("CName")]
[string[]] $ComputerName
)
foreach($cName in $ComputerName)
{
Write-Verbose "Testing connection to $cName"
If (Test-Connection -ComputerName $cName -BufferSize 16 -Quiet)
{
Write-Verbose "Connection successful."
Write-Verbose "Obtaining WMI objects from $cName"
$cs = Get-WMIObject -Class Win32_ComputerSystem -ComputerName $cName
$csp = Get-WMIObject -Class Win32_ComputerSystemProduct -ComputerName $cName
$os = Get-WMIObject -Class Win32_OperatingSystem -ComputerName $cName
$bios = Get-WMIObject -Class Win32_BIOS -ComputerName $cName
$cpu = Get-WMIObject -Class Win32_Processor -ComputerName $cName
$hdd = Get-WMIObject -Class Win32_LogicalDisk -Filter 'DeviceID = "C:"' -ComputerName $cName
$network = Get-WMIObject -Class Win32_NetworkAdapterConfiguration -Filter 'DHCPEnabled = True' -ComputerName $cName
if ($hdd -is [System.array])
{
Write-Verbose "Multiple hard drives detected; using first result"
$hddResult = $hdd[0]
} else {
Write-Verbose "Single hard drive detected"
$hddResult = $hdd
}
if ($network -is [System.array])
{
Write-Verbose "Multiple network cards detected; using first result"
$networkResult = $network[0]
} else {
Write-Verbose "Single network card detected"
$networkResult = $network
}
Write-Verbose "Creating output table"
$props = @{'Name' = $cs.Name;
'OSVersion' = $os.Version;
'ServicePack' = $os.ServicePackMajorVersion;
'HardDiskSize' = $hddResult.Size;
'SerialNumber' = $bios.serialNumber;
'Model' = $cs.Model;
'Manufacturer' = $cs.Manufacturer;
'Processor' = $cpu.Name;
'RAM' = $cs.TotalPhysicalMemory;
'MACAddress' = $networkResult.MACAddress}
Write-Verbose "Creating output object from table"
$result = New-Object -TypeName PSObject -Property $props
Write-Verbose "Outputting result"
$resultArray += @($result)
} else {
Write-Verbose "Connection failure"
$resultArray += @($null)
}
}
Write-Output $resultArray
}
这是一个运行示例,为了更清楚起见。数据是假的,但这是结果的格式:
PS> 获取-PCInfo localhost
SerialNumber : 12345
MACAddress :
RAM : 4203204608
Manufacturer : Computers, Inc.
Processor : Intel(R) Core(TM) i5-2400 CPU @ 3.10GHz
HardDiskSize : 500105736192
OSVersion : 6.2.9200
Name : PC1
Model: : Super Awesome Computer
ServicePack : 0
我想将此发送到 ConvertTo-HTML 或其他东西以制作漂亮的报告,但由于MACAddress
是空白的,我无法从中做出任何漂亮的东西。我想看到的是这样的:
SerialNumber : 12345
MACAddress[0] : 00-11-22-33-44-55
MACAddress[1] : 88-99-AA-BB-CC-DD
...
HardDiskSize[0]: 500105736192
HardDiskSize[1]: 500105736192