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 count(r.session_id) as NbrequetesEnCours FROM sys.dm_exec_requests r join sys.dm_exec_sessions ses on ses.session_id = r.session_id CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t CROSS APPLY sys.dm_exec_query_plan(r.plan_handle) AS p"

$DataTexte = $Liste.NbrequetesEnCours

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
}