I am creating a script to read CPU and Memory data in a specific time and exporting that to an excel spreadsheet.
Everything seems to work correctly until it gets to the " $sheet.Cells.Item($rowStartTime+$i,$colStartTime).value = $StartTime" where I post the date and time on a cell.
I tested changing the $StartTime variable for a string like "TIME" and it writes to the cell but if I do and $StartTime = $StartTime.ToString() I get the same "Specified cast is not valid" error, what makes me think the problem might be related with the date format.
Below the script, any help is appreciated.
$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