I'm trying to have powershell see if there is data in a certain cell, as no action is needed if it is blank.
Here's what I have so far:
$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Open('MySheet.xlsx')
$workSheet = $Workbook.Sheets.Item(1)
$WorkSheet.Name
$column = 1
$row = 2
$info = $workSheet.cells.Item($row, $column).text
#$excel.Quit()
echo $info
$info of course has nothing in it.
Basically, if cell A2 is blank, I'm going to exit, otherwise I'll send an email, etc. I guess I'm asking do I convert $info to string?
I've tried
If($info = "")
and
If($info -eq null)
but I guess I'm stuck on where to go now. How do I tell the computer "Hey, if there is anything in cell A2, do this"
Thanks in advance for any help.
The .text
retrieves the value of the cell as string. If that is not what you want, use .Value2
to get the underlying value of the cell (can be a string, a double, etc).
To fix what you have tried with If($info = "")
:
=
is an assignment, not a comparison operator, so in this case you would be better off using -eq
or even better If([string]::IsNullOrWhiteSpace($info))
Also, remember that you need to remove the used COM objects from memory when done, otherwise eventually these will gobble up your computers memory.
Your code rewritten in full:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$workbook = $excel.Workbooks.Open("D:\Test\MySheet.xlsx")
$workSheet = $Workbook.Sheets.Item(1)
$column = 1
$row = 3
$info = $workSheet.Cells.Item($row, $column).Text
if (-not [string]::IsNullOrWhiteSpace($info)) {
# cell was not empty, so do what you need to do with $info
write-host $info
}
# we're done, so quit Excel and clean-up the COM objects used
$workbook.Close()
$excel.Quit()
# cleanup COM objects
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workSheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Thank you so much. Theo!