Write-Host "SUCCESS_POWERSHELL"
$dsnName = "<DSN_NAME>"
$user = "<USER>"
$password = "<PASSWORD>"
$csvPath = "<CSV_PATH>"
$logPath = "<LOG_PATH>"
$token = "<TOKEN>"
$newlineToken = "<NEWLINE_TOKEN>"
$databaseName = "<DATABASE_NAME>"
$maxRows = <MAX_ROWS>
$connString = "DSN=$dsnName;Uid=$user;Pwd=$password;"
$sqlQuery = "<QUERY>"

$conn = New-Object System.Data.Odbc.OdbcConnection
try {
	
	Write-Host "Setting Connection String"
	$conn.ConnectionString = $connString
	
    Write-Host "Attempting Connection $dsnName $user $sqlQuery"
    
    $conn.Open()
    Write-Host "SUCCESS_CONNECTION"
    
    if ($databaseName) {
    	Write-Host "Execute use $databaseName query"
   		$useDbCommand = New-Object System.Data.Odbc.OdbcCommand("USE $databaseName", $conn)
		$useDbCommand.ExecuteNonQuery() | Out-Null
		Write-Host "Done execute use query"
    }

	Write-Host "Creating command"
	
	$odbcCommand = New-Object System.Data.Odbc.OdbcCommand $sqlQuery, $conn
	
	Write-Host "Creating reader"
	$reader = $odbcCommand.ExecuteReader()
	Write-Host "SUCCESS_QUERY"
	
	$stringBuilder = New-Object System.Text.StringBuilder
	$index = 0;
	$fieldCount = 0
	
	Write-Host "Getting data"
	$rowCount = 0
    while ($reader.Read() -and $rowCount -lt $maxRows)
	{
		$rowCount = $rowCount + 1
		if ($index -eq 0)
		{
			$fieldCount = $reader.FieldCount
			for ($x=0; $x -lt $fieldCount; $x++)
			{
				if ($x -lt 1)
				{
					[void]$stringBuilder.append($reader.getName($x))
				}
				else
				{
					[void]$stringBuilder.append($token + $reader.getName($x))
				}
			}
			[void]$stringBuilder.append($newlineToken)
			for ($x=0; $x -lt $fieldCount; $x++)
			{
				if ($x -lt 1)
				{
					[void]$stringBuilder.append($reader.getDataTypeName($x))
				}
				else
				{
					[void]$stringBuilder.append($token + $reader.getDataTypeName($x))
				}
			}
			[void]$stringBuilder.append($newlineToken)
		}
		$index = 1
		$found = 0
		for ($x=0; $x -lt $fieldCount; $x++)
		{
			try
			{
				$value = $reader.getString($x)	
			}
			catch 
			{
				$value = $reader.getValue($x).toString()	
			}
			if ([string]::IsNullOrEmpty($value))
			{
				$value = "||NULL_VALUE||"
			}
			if ($x -lt 1)
			{
				$found = 1
				[void]$stringBuilder.append($value)
			}
			else
			{
				$found = 1
				[void]$stringBuilder.append($token + $value)
			}	
		}
		if ($found -gt 0)
		{
			[void]$stringBuilder.append($newlineToken)
		}
 	}
	$reader.Close();
	  
	Write-Host "Writing Output"
	Write-Output $stringBuilder.toString() | Out-File -FilePath $csvPath -Encoding Utf8
	
	Write-Host "Process Complete"
	Write-Host "SUCCESS_PROCESS"
}
catch {
    Write-Host "An error occurred: $_.Exception.Message"
    Add-Content -Path $logPath -Value "An error occurred: $_.Exception.Message"
}
finally {
    if ($conn.State -eq 'Open') {
        $conn.Close()
        Write-Host "Connection closed."
    }
}