我正试图通过powershell从excel数据创建条形图。
在excel文件中,我有包含硬件型号的计算机列表。我试图通过硬件模型获得设备组的总数。
e.g.
HP- 50
Dell - 100
IBM -10
这是我到目前为止编写的代码。
#Declare the file path and sheet name
$file = "D:\HealthCheck_test.xlsx"
$sheetName = "DC01"
#Create an instance of Excel.Application and Open Excel file
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false
#$red = 1;
#$orange = 1;
#Count max row
$rowMax = ($sheet.UsedRange.Rows).count
#Declare the starting positions
$rowHB,$colHB = 5,14 #pie
$rowModel,$colModel = 5,32 #bar
$rowHWInv,$colHWInv = 5,16 #Pie
$rowSite,$colSite = 5,40 #Bar
$rowOS,$colOS = 5,41 #Bar
#array to get 2d data for bar chart
$arr=@{}
$arr["model"] = @{}
$arr["model"]["type"] = @{}
#loop to get values and store it
for ($i=1; $i -le $rowMax-1; $i++)
{
$HB = $sheet.Cells.Item($rowHB+$i,$colHB).text
$Model = $sheet.Cells.Item($rowModel+$i,$colModel).text
$HWInv = $sheet.Cells.Item($rowHWInv+$i,$colHWInv).text
$Site = $sheet.Cells.Item($rowSite+$i,$colSite).text
$OS = $sheet.Cells.Item($rowOS+$i,$colOS).text
#$i
Write-Host ("I am reading data on row: "+$i)
[int] $hb = $HB
$arr["model"]["type"] = $Model
[int] $HWInv = $HWInv
$Site = $Site
$OS = $OS
if($hb -ge 31){
$red = $red + 1
}
if($hb -ge 14 -and $hb -le 30){
$orange = $orange + 1
}
}
$objExcel.quit()
Write-Host ("Total devices more than 30 days old: "+$red)
Write-Host ("Total devices 14-30 days old: "+$orange)
上面的代码工作正常,但它没有返回模型类型的数据。
我以为我需要使用2d数组来存储硬件类型数据。因此,在我可以按模型类型获取数据之后,所有数据都将存储在数组中。任何人都可以就此提出建议。我不知道我该怎么做?
Name Days Since PWD Model Manufacturer
desktop 40 OptiPlex 790 Dell Inc.
lappy 15
test 209
test2 51
test5 27 OptiPlex XE2 Dell Inc.
答案 0 :(得分:1)
首先使用@{}
创建哈希表,而不是数组。
其次,数组的索引是全数字的,因此即使正确声明$arr
,您的方法也会失败。在你的代码示例中,我甚至没有看到除了一个简单的数组之外还需要使用任何东西,因为你只存储一个值(也许你的例子不完整或者我错过了什么?)
在阅读完评论后,我们可以简化这一点。
在循环之前创建一个空数组:
$arr= @()
在循环中将模型值添加到数组中:
$arr+=$model
循环后,您可以计算每个制造商的出现次数:
($arr | where {$_ -like "*HP*"}).count
例如,您将给出模型值包含“HP”的次数,您可能需要调整您要查找的字符串,但这基本上可以正常工作