在While循环中将表行计数与同一表的上一个表行计数进行比较

时间:2019-10-10 17:47:41

标签: sql powershell

试图了解让表读取SQL表行计数的基本逻辑-存储该值。 下次读取表时-如果行数增加,则只能执行某些操作(在这种情况下,将事件写入MS日志文件)。 基本上-寻找已添加到帐户中以触发事件的新行。

while($ true)用于使此PowerShell脚本在后台无限期运行-因此,这是使用睡眠来间歇性检查表状态

    while($true)
{
### there’s a bunch of code to make the connection and variables set before this: 

$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
[void]$DataAdapter.Fill($dataset)
$DataSet.Tables[0].'Table Name'
$sqlConnection.Close()
$sqlConnection.Dispose()


### set the number of rows in table since last count 

$dataset.Tables[0].Rows.Count | set-content set.txt

$LastRowCount = Get-Content set.txt #this is where I’m stuck on how to apply this last count
                                    #do I need another loop inside?

if($dataset.Tables[0].Rows.Count -gt 0 -and $dataset.Tables[0].Rows.Count -gt $LastRowCount) {

     write-Eventlog –LogName HUGs –Source Exciter –EventID 101 -Message "testing 123"
 }
 else{
      Write-Host "NO CHANGE IN RECORD COUNT FROM LAST RUN"

     } 
#TAKE A FIVE MINUTE BREAK
Start-Sleep -Seconds 30 

 }

1 个答案:

答案 0 :(得分:0)

您需要2个变量,但我对powershell不熟悉,所以只是一些伪代码

$LastRowCount = Get-Content; // Set the variable before the loop

while($true)
{ 
  $CurrentRowCount = Get-Content; // Get the update count

 If $LastRowCount <> $CurrentRowCount then 
 {
    write-Eventlog –LogName HUGs –Source Exciter –EventID 101 -Message "testing 123"
    $LastRowCount = $CurrentRowCount // Update the variable for the next loop

 } else {
    Write-Host "NO CHANGE IN RECORD COUNT FROM LAST RUN"
 }