如何提取服务器信息

时间:2015-07-13 14:26:56

标签: powershell server wmi

目标:如何提取服务器信息?

对于servers.txt中列出的每个服务器名称,我想获得以下信息(采用此格式):

服务器名称,IP地址,操作系统名称,总物理内存,处理器,每个驱动器号和大小,系统型号

每个服务器的逗号分隔和新行。

以下是我的PowerShell代码。你的家伙可以暗示为什么这不起作用?另外,为什么我在New-Object语句中出错?

foreach ($ComputerName in (Get-Content -Path .\servers.txt)) {
  $HashProps = @{
    'tHostname' = Get-WmiObject Win32_Computersystem -ComputerName $ComputerName | Select-Object -ExpandProperty Name
    'tIP' = [System.Net.Dns]::GetHostAddresses($computername)
    'tOS' = Get-WmiObject -ComputerName $ComputerName -Class Win32_OperatingSystem | Select-Object -ExpandProperty Caption
    'tMemory' = Get-WmiObject Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | foreach { "$("{0:n2}" -f ( $_.Sum/1GB ) )" }
    'tcpu' = Get-WmiObject Win32_processor | Select-Object name, numberofcores
    'tDisks' = Get-WmiObject Win32_LogicalDisk | foreach { "$($_.DeviceID) $("{0:n2}" -f ( $_.Size/ 1GB ) )" }
    'tsysmodel' = Get-Wmiobject Win32_computersystem | Select-Object model
  }
  New-Object -TypeName psObject -Property $HashProps |
  ConvertTo-Csv -NoTypeInformation | Out-File -Append .\output.csv
}

如果这更容易,我愿意采取其他方法。

2 个答案:

答案 0 :(得分:0)

您是否确认每条线路实际上都返回了您想要的内容?

我把它扔进了ISE,它运行良好:

$f = gwmi win32_computersystem | select name,model,totalphysicalmemory
$hash = @{
    'name' = $f.name
    'model' = $f.model
    'memory' = $("{0:n2}" -f ( $f.totalphysicalmemory/1GB ) )
}
New-Object -TypeName psobject -Property $hash | ConvertTo-Csv -NoTypeInformation | Out-File -Append .\test.csv

此外,如果您希望属性在CSV中以特定顺序显示,则需要一些额外的魔法,否则它们将按字母顺序排列。

答案 1 :(得分:0)

有点拉皮条,也许这会对你有所帮助:

$Servers = Foreach ($ComputerName in (Get-Content -Path .\Servers.txt)) {
    $CS = Get-WmiObject Win32_ComputerSystem -ComputerName $ComputerName
    $OS = Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName
    $PM = Get-WmiObject Win32_PhysicalMemory -ComputerName $ComputerName
    $PR = Get-WmiObject Win32_processor -ComputerName $ComputerName
    $LD = Get-WmiObject Win32_LogicalDisk -ComputerName $ComputerName
    $IP = [System.Net.Dns]::GetHostAddresses($ComputerName)

    [PSCustomObject]@{
        ServerName = $CS | Select-Object -ExpandProperty Name
        IPAddress  = $IP | Select-Object -ExpandProperty IPAddressToString
        OS         = $OS | Select-Object -ExpandProperty Caption
        Memory     = $PM | Measure-Object -Property Capacity -Sum | foreach { "$("{0:n2}" -f ( $_.Sum/1GB ) )" }
        CPU        = $PR | Select-Object Name, NumberOfCores
        Disks      = $LD | foreach { "$($_.DeviceID) $("{0:n2}" -f ( $_.Size/ 1GB ) )" }
        Model      = $CS | Select-Object -ExpandProperty Model
    }
}

$File = Join-Path $env:TEMP 'Ouptut.csv'
$Servers | Export-Csv -Path $File -NoTypeInformation -Delimiter ';'
Start-Process $File