Function QuerySQLServer([string]$DBServer, [string]$DBName, [string]$Query) {
    Try {
        $ErrorActionPreference = "Stop"
   
        $resultsDataTable = New-Object System.Data.DataTable

        $cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
        $cn.open()
 
        $cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
        $reader = $cmd.ExecuteReader()

        $resultsDataTable.Load($reader)

        $cn.Close()

        return $resultsDataTable
    }
    Catch {
        write-host $_.Exception.Message
        $_.Exception.Message >> "d:\error.log"
    }
    Finally {
     $ErrorActionPreference = "Continue"
    }
}

cls

$bReturnOK = $TRUE
$bReturnCritical = $FALSE
$bReturnWarning = $FALSE
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3

$strCritical = ""
$strWarning  = ""
$DataTexte   = ""

$ComputerName = $env:COMPUTERNAME

$Liste = QuerySQLServer "$ComputerName" "dhb_prd" "SELECT A.session_id, Db_Name(database_id) AS [database], DateDiff(MINUTE, A.connect_time, GetDate()) AS [Connected (mins)], num_reads, num_writes, login_name, Text AS SQL FROM sys.dm_exec_connections AS A INNER JOIN sys.dm_exec_sessions AS B ON A.session_id = B.session_id INNER JOIN sys.sysprocesses AS s ON s.spid = A.session_id OUTER APPLY::fn_get_sql(sql_handle)"
$Liste | Format-Table | Out-String|% {Write-Host $_}

$DataTexte = $Liste.login_name

If ($bReturnCritical) {
    write-output $strCritical
    write-output $strWarning "|" $DataTexte
    exit $returnStateCritical
}
Elseif ($bReturnWarning) {
    write-output $strWarning "|" $DataTexte
    exit $returnStateWarning
}
Else {
    write-output "OK - Nombre de requete en cours : $DataTexte | 'NbrequetesEnCours'=$DataTexte "
    exit $returnStateOK
}