我正在创建一个脚本以在特定时间内读取CPU和内存数据,并将其导出到Excel电子表格。
一切似乎都能正常工作,直到到达“ $ sheet.Cells.Item($ rowStartTime + $ i,$ colStartTime).value = $ StartTime”为止,在这里我将日期和时间发布到单元格上。
我测试了将$ StartTime变量更改为诸如“ TIME”之类的字符串,并将其写入单元格,但是如果我这样做并且$ StartTime = $ StartTime.ToString()我得到相同的“指定的转换无效”错误,是什么让我认为问题可能与日期格式有关。
在脚本下面,我们将提供任何帮助。
$timeout = new-timespan -Minutes 10
$file = "C:\Users\i859241\Desktop\resultilz.xlsx"
$sheetName = "UNO"
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false
$i=0
$rowStartTime,$colStartTime = 2,1
$rowCPULoad,$colCPULoad = 2,2
$rowpctFree,$colpctFree = 2,3
$sw = [diagnostics.stopwatch]::StartNew()
Get-WmiObject -Class Win32_logicaldisk
while ($sw.elapsed -lt $timeout){
$StartTime = Get-Date
$os = Get-Ciminstance Win32_OperatingSystem
$CpuLoad = (Get-WmiObject win32_processor | Measure-Object -
property LoadPercentage -Average | Select Average ).Average
pctFree =[math]::Round(($os.FreePhysicalMemory/$os.TotalVisibleMemorySize)*100,2)
Write-Host $StartTime, $pctFree, $CpuLoad
$sheet.Cells.Item($rowStartTime+$i,$colStartTime).value = $StartTime
$sheet.Cells.Item($rowCPULoad+$i,$colCPULoad).value = $CPULoad
$sheet.Cells.Item($rowpctFree+$i,$colpctFree).value = $pctFree
start-sleep -seconds 2
}
write-host "Timed"
$workbook.save()
$workbook.close()
$objExcel.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)
Stop-Process -Name EXCEL -Force
答案 0 :(得分:0)
尝试一下:
$timeout = new-timespan -Minutes 10
$file = "C:\Temp\resultilz.xlsx"
$sheetName = "UNO"
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false
$row=1
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timeout){
$StartTime = Get-Date
$os = Get-Ciminstance Win32_OperatingSystem
$CpuLoad = (Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average ).Average
$pctFree =[math]::Round(($os.FreePhysicalMemory/$os.TotalVisibleMemorySize)*100,2)
Write-Host $StartTime, $pctFree, $CpuLoad
$sheet.Cells.Item($row,1).value = [string]$StartTime
$sheet.Cells.Item($row,2).value = [string]$pctFree
$sheet.Cells.Item($row,3).value = [string]$CpuLoad
$row++
start-sleep -seconds 2
}
write-host "Timed"
$workbook.save()
$workbook.close()
$objExcel.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)
Stop-Process -Name EXCEL -Force