0
Street City Hour of Registration
hill st bolton 11/16/2022 10:00
flo st bolton 11/15/2022 10:10

If city=bolton AND Hour of Registration less than or qual to <= 24hrs then delete Row

So basically, if I run the code against a xls file with the dataset above, only Row 1 (hill st) should be deleted. Basically something like current time - hour of registration.

The code I have below is able to delete a row given 1 condition but I'm not sure how to implement multiple conditions or the time

Count is bottom up. Top down seems to mess up the counting and miss some rows

$file  = 'salehouses.xls'
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
# open file
$workbook = $excel.Workbooks.Open($file)
$sheet    = $workbook.Worksheets.Item(1)
# get max rows
$rowMax   = $sheet.UsedRange.Rows.Count

for ($row = $rowMax; $row -ge 2; $row--) {
    $cell = $sheet.Cells[$row, 2].Value2
    if ($cell -ieq 'bolton') {
        $null = $sheet.Rows($row).EntireRow.Delete() }

$Filename = 'salehouses.xls'
$workbook.SaveAs("c:\xls\salehouses.xls")
$excel.Quit()


Bigger Data set to test against as of 11/17/2022 3:50 PM where everything <24hr should be deleted. 

Street  City    Hour Of Registeration   
hill st     Bolton  11/16/2022 12:28    >24hr
flow st Bolton  11/16/2022 13:39    >24hr
jane st Bolton  11/16/2022 15:00    >24hr
jack st     Bolton  11/16/2022 15:00    >24hr
Gone st Bolton  11/16/2022 18:16    <24hr
top st  Bolton  11/16/2022 18:27    <24hr
sale st     Bolton  11/16/2022 19:18    <24hr
jack st     Bolton  11/16/2022 20:14    <24hr
Gone st Bolton  11/16/2022 20:28    <24hr
top st  Bolton  11/17/2022 02:51    <24hr
sale st     Bolton  11/17/2022 03:02    <24hr
jack st     Bolton  11/17/2022 06:21    <24hr
Gone st Bolton  11/17/2022 08:51    <24hr


2 Answers 2

1

Here is a working solution.

$file  = 'salehouses.xlsx'
$sourcePath = 'C:\some\path\'
$sourceFile = $sourcePath + $file

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
# open file
$workbook = $excel.Workbooks.Open($sourceFile)
$sheet    = $workbook.Worksheets.Item(1)
# get max rows
$rowMax   = $sheet.UsedRange.Rows.Count

# start at last row
for ($rowNumber=$rowMax; $rowNumber -ge '2'; $rowNumber--){
    $city = $sheet.Cells($rowNumber,2).value2
   
    if ($sheet.Cells($rowNumber,3).text -ne $null -and $sheet.Cells($rowNumber,3).text -ne ""){
         # 24 hour format
        $regTime = get-date -Format "MM/dd/yyyy HH:mm" $sheet.Cells($rowNumber,3).text
        # 24 hour format
        $currentTime = Get-Date -Format "MM/dd/yyyy HH:mm"        
       
        $timeDifference = (NEW-TIMESPAN -Start $regTime -End $currentTime)
        Write-Host "time difference (hours): " $timeDifference.TotalHours

        if ($city -eq "bolton" -and $timeDifference.TotalHours -le '24') {
            Write-Host "Delete"
            $null = $sheet.Rows($rowNumber).EntireRow.Delete() 

        }
    }
}







$Filename = 'salehouses_modified.xlsx'
$path = 'c:\some\path\'
$fullPathModified =$path + $Filename
$workbook.SaveAs($fullPathModified)
$excel.Quit()

Source for getting time difference

Notes

In your original code you have the right idea of getting the used range count and looping through that and also not reading the header. You also were able to compare one cell you just needed to grab the cell in the hours column as well.

If you want to do something based on multiple conditions being met use -and in the if statement.

One quirk you may notice is when getting the date cell I had to use .text instead of .value2 like the other cell. I'm not exactly sure why but I think it's because excel formatted the cell as a date and it had a different format stored in .value2 while .text held the value we wanted.

I would recommend practicing using different conditional statements and the Get-Date command like the other commenter suggested, to get more comfortable with what's happening in the above code.

Some Edits

There were some issues with my code. Starting at 0 and counting up in the for loop is incorrect as rows are being deleted and the numbering gets thrown off. Starting at last row and counting down fixes issue.

The second issue was the times were in 24-hour format which I didn't catch originally. Fixed the code Get-Date -Format "MM/dd/yyyy HH:mm" so it read both the registration time and current time as 24-hour format. The time comparison for totaling hours was also off. Using .TotalHours instead of .hours like I had it gives the correct difference.

Sign up to request clarification or add additional context in comments.

4 Comments

Hey Thank for the answer but I am getting this error: Get-Date : Cannot bind parameter 'Date'. Cannot convert value "" to type "System.DateTime". Error: "String was not recognized as a valid DateTime." Get-Date : Cannot bind parameter 'Date'. Cannot convert value "" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
@NebelzCheez I added some explanations to my post. One of the cells being read was blank. That's why the error message contains empty qoutes "". I added an if statment to check for this as well if it's a null value. if ($sheet.Cells($rowNumber,3).text -ne $null -and $sheet.Cells($rowNumber,3).text -ne "")
Hey, the script misses to delete some rows that should be deleted. This might be because you are counting from top down. Can you try with bottom up? Sometimes it deletes rows that shouldn't be deleted. Not sure if that's to do with 24hr timing or count from top down. I added some data set you can test against. For some reason rows >24hr get deleted :)
@NebelzCheez you are correct. I didn't realize it was in 24 hour format. Please see the changes. Also checkout the Get-Date -Format parameter if you need to make any changes to the time format. How I had the loop was also wrong, how you had it originally counting down from the top is correct.
1

To calculate the time difference, you can try yourself for understanding.

[DateTime]$HourofReg = "11/16/2022 10:00" #To convert the string to DateTime
$currentTime = Get-date
$timeDiff = New-TimeSpan $HourofReg $currentTime # To find the time difference
if ( $timeDiff.TotalHours -gt 24) {
Write-Host "greater than 24 hours"
}

To answer your question: Get the hourofreg cell value in a variable and do the above steps.

if ( ($cell -ieq 'bolton') -and ($timeDiff.TotalHours -gt 24 )) {
 # Do Something 
}
Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.