城市 | 登记时间 | 山圣道明> | 11/16/2022 10点 |
---|---|
弗洛圣道明> | 11/15/2022 10:10 |
这是一个可行的解决方案。
$file = 'salehouses.xlsx'
$sourcePath = 'C:somepath'
$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:somepath'
$fullPathModified =$path + $Filename
$workbook.SaveAs($fullPathModified)
$excel.Quit()
时差获取源
指出在你的原始代码中,你有正确的想法,获得使用的范围计数和循环,也不读取头。您还可以比较一个单元格,您只需要在小时列中获取单元格。
如果你想在满足多个条件的基础上做一些事情,在If语句中使用-and
。
你可能会注意到的一个怪癖是,当获得日期单元格时,我不得不使用.text
而不是.value2
,就像其他单元格一样。我不太确定为什么,但我认为这是因为excel格式化单元格作为一个日期,它有一个不同的格式存储在。value2而。text持有我们想要的值。
我建议像其他评论者建议的那样练习使用不同的条件语句和Get-Date
命令,以便对上面代码中发生的事情更熟悉。
我的代码有些问题。从0开始并在for循环中向上计数是不正确的,因为行被删除并且编号被丢弃。从最后一行开始倒数修复了这个问题。
第二个问题是时间是24小时制的,我一开始没有注意到。修正了代码Get-Date -Format "MM/dd/yyyy HH:mm"
,因此它读取注册时间和当前时间为24小时格式。总小时数的时间比较也关闭了。使用.TotalHours
代替.hours
,就像我一样,它给出了正确的差异。
要计算时差,您可以自己试着理解。
[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"
}
回答你的问题:在变量中获取小时freg单元格值并执行上述步骤。
if ( ($cell -ieq 'bolton') -and ($timeDiff.TotalHours -gt 24 )) {
# Do Something
}
Hope this helps!