1

我有以下代码,它可以工作。但我想知道这是否是最好的方法,因为它一遍又一遍地重复结构。

$Computers = Get-Content -Path C:\scripts\Computers.txt
$AllComputers = @()
foreach ($machine in $Computers) {
  $objCompSys = Get-WmIObject -class "Win32_ComputerSystem" -cn $machine -EA silentlyContinue  -namespace "root\CIMV2"
  foreach ($item in $objCompSys) {
    $compname = $item.Name
    $physicalRAM = [Math]::Ceiling($item.TotalPhysicalMemory / 1MB)
    $numProcs = $item.NumberOfProcessors
  }
  $objProc = Get-WMIObject -class "Win32_Processor" -cn $machine -EA silentlyContinue -namespace "root\CIMV2"
  foreach ($item in $objProc) {
    $procType = $item.Name
    $procSpeed = $item.MaxClockSpeed
  }
  if (procSpeed -eq "486") {
    $Data1 = @{
      MachineName    = $compname
      CPUSpeed       = $procSpeed
      "Num CPUs"     = $numProcs
      "Physical RAM" = $physicalRAM
      "Summary"      = "486 process - check"
      New-Object PSObject -Property $data1
    }
    $AllComputers += $Data1
  } elseif (procSpeed -eq "586") {
    $Data2 = @{
      MachineName    = $compname
      CPUSpeed       = $procSpeed
      "Num CPUs"     = $numProcs
      "Physical RAM" = $physicalRAM
      "Summary"      = "586 process - check"
      New-Object PSObject -Property $data2
    }
    $AllComputers += $Data2
  } else (procSpeed -eq "6*") {
    $Data3 = @{
      MachineName    = $compname
      CPUSpeed       = $procSpeed
      "Num CPUs"     = $numProcs
      "Physical RAM" = $physicalRAM
      "Summary"      = "New Models - Good to go"
      New-Object PSObject -Property $data3
    }
    $AllComputers += $Data3
  }
}

$AllComputers | Out-GridView
4

1 回答 1

1

是的。设置一次“数据”表,然后在必要时仅更改“摘要”字段:

$Computers = Get-Content -Path C:\scripts\Computers.txt
$AllComputers = @()
foreach($machine in $Computers)
{
    $objCompSys = Get-WmIObject -class "Win32_ComputerSystem" -cn $machine -EA silentlyContinue  -namespace "root\CIMV2"
    foreach($item in $objCompSys)
    {
        $compname = $item.Name
        $physicalRAM = [Math]::Ceiling($item.TotalPhysicalMemory / 1MB)
        $numProcs = $item.NumberOfProcessors
    }

    $objProc = Get-WMIObject -class "Win32_Processor" -cn $machine -EA silentlyContinue  -namespace "root\CIMV2"
    foreach($item in $objProc)
    {
        $procType = $item.Name
        $procSpeed = $item.MaxClockSpeed
    }
    $Data = @{
        MachineName    = $compname
        CPUSpeed       = $procSpeed
        "Num CPUs"     = $numProcs
        "Physical RAM" = $physicalRAM  
    }

    $Data["Summary"] = switch($procSpeed)
    {
        "486" { "486 process - check" } 
        "586" { "586 process - check" } 
        default { "New Models - Good to go" }
    }

    $AllComputers += New-Object psobject -Property $Data
}
$AllComputers | Out-GridView

以上switch与此 if/else 构造相当:

if($procSpeed -eq "486") { 
    "486 process - check" 
} elseif($procSpeed -eq "486") { 
    "586 process - check"
} else { 
    "New Models - Good to go" 
}
于 2015-08-10T19:19:26.920 回答