通过IP地址循环

时间:2019-03-07 05:35:25

标签: powershell for-loop

我有一个工作代码来检查房屋中每个单元的公羊数量。我给它提供了一个IP地址,它返回了ram的数量以及其他所有格式正确的内容。我可以在其中添加一个预先完成的文件,以使其接受来自.txt或.csv的IP列表吗?

我试图将这段代码粘贴到另一个不在列表中的文件中,但是我一直遇到错误。

param([string]$fileInput,[string]$fileOutput )

If ( $fileInput -eq "" -OR $fileOutput -eq ""){ 
    $list =  Import-Csv $fileInput -Header name, licenseKey, keyStatus

    foreach( $computerName in $list){
          export-csv -InputObject $computerName -append $fileOutput -Encoding utf8
    }
}

我不确定代码中这些行的正确位置。

write-host ""
$strComputer = Read-Host "Enter Computer Name to list memory slot information"
$colSlots = Get-WmiObject -Class "win32_PhysicalMemoryArray" -namespace "root\CIMV2" -computerName $strComputer
$colRAM = Get-WmiObject -Class "win32_PhysicalMemory" -namespace "root\CIMV2" -computerName $strComputer
$NumSlots = 0

write-host ""
$colSlots | ForEach {
  “Total Number of Memory Slots: ” + $_.MemoryDevices
  $NumSlots = $_.MemoryDevices
}

write-host ""
Read-Host "Press Enter to continue"

$SlotsFilled = 0
$TotMemPopulated = 0

$colRAM | ForEach {
   “Memory Installed: ” + $_.DeviceLocator
   “Memory Size: ” + ($_.Capacity / 1GB) + ” GB”       
   $SlotsFilled = $SlotsFilled + 1
   $TotMemPopulated = $TotMemPopulated + ($_.Capacity / 1GB)
#      if ($_.Capacity = 0)
#      {write-host "found free slot"}

}

write-host ""
write-host "=== Summary Memory Slot Info for computer:" $strComputer "==="
write-host ""
If (($NumSlots - $SlotsFilled) -eq 0) {
    write-host "ALL Slots Filled, NO EMPTY SLOTS AVAILABLE!"
}
write-host ($NumSlots - $SlotsFilled) " of " $NumSlots " slots Open/Available (Unpopulated)"
write-host ($SlotsFilled) " of " $NumSlots " slots Used/Filled (Populated)."  
write-host ""
write-host "Total Memory Populated = " $TotMemPopulated "GB"

#

1 个答案:

答案 0 :(得分:0)

foreach循环将是惯用的解决方案。

创建一个包含计算机名称或IP地址的文本文件,如下所示:

computer1
computer2
...
computern

也就是说,每个系统名称或地址都在其自己的行中,没有任何多余的内容。很简单,对不对?将其另存为c:\temp\computersToCheck.txt。在获得名称列表之后,请更改代码以支持上述foreach循环。

# Read all the computers from the file
$computers = get-content c:\temp\computersToCheck.txt

# Perform an operation for each row in the file
foreach ($strComputer in $computers) {
    $colSlots = Get-WmiObject -Class "win32_PhysicalMemoryArray" -namespace "root\CIMV2" -computerName $strComputer
    # Rest of the code goes here
...
write-host "Total Memory Populated = " $TotMemPopulated "GB"
}