$sqlConnection = New-Object System.Data.SqlClient.SqlConnection 
$sqlConnection.ConnectionString = 'Server=rejk-p-sql003\sql01;Database=SMCDB;Trusted_Connection=True;'
$sqlConnection.Open()
$sqlCommand = $sqlConnection.CreateCommand()


$sqlCommand.CommandText = @"
SELECT [eventId]
      --,[description]
      --,[eqptValue]
      ,[explanation]
      ,[generationDate]
      ,[type]
      ,[receptionDate]
      ,[source]
      ,[sourceSamId]
	  ,[sourceLabelName]
      ,[sourceLocalization]
      ,[sourceOperator]
      ,[sourceContractor]
	  
  FROM [SMCDB].[dbo].[STCS_Event]

  where type = 'VAL_MODE' and generationdate > '2017-12-15'
  order by source, generationDate
"@

$reader = $sqlCommand.ExecuteReader()

if($reader.HasRows) {
    $i = 0
    
    while($true) {
        $data = while($morerows = $reader.read()) {
        
            [pscustomobject]@{
                eventId = $reader['eventId']
                explanation = $reader['explanation']
                generationDate = $reader['generationDate']
                type = $reader['type']
                receptionDate = $reader['receptionDate']
                source = $reader['source']
                sourceSamId = $reader['sourceSamId']
                sourceLocalization = $reader['sourceLocalization']
                sourceOperator = $reader['sourceOperator']
                sourceContractor = $reader['sourceContractor']
            }

            $i++

            if($i % 10000 -eq 0) { 
                Write-Verbose "row $i" -verbose
                break
            }
        }

        $data | Export-Csv -Delimiter "`t" -NoTypeInformation -Path C:\users\ewpmni\desktop\ValMode.csv -Append -Encoding utf8

        if(-not $morerows) {
            break
        }
    }
}



$reader.Close()
$sqlConnection.Close()

