如果SQL结果为空,则输出错误

时间:2014-01-23 13:59:22

标签: sql powershell

我正在运行执行查询的powershell脚本,并连续输出记录。

如果查询未在数据库中找到记录,如何输出通知?

我试图评估$ rdr是否为$ NULL,但整个输出为空,就好像数据库中没有文件中的IP地址一样:

foreach ($k in $file){


    $conn.Open()

    $sql = "SELECT dbo.sem_computer.COMPUTER_NAME,[IP_ADDR1_TEXT],(dbo.SEM_AGENT.FREE_DISK/1073741824)as 'Free Disk Space (GB)', 
    (dbo.SEM_COMPUTER.DISK_TOTAL/1073741824) as 'Total Disk Space (GB)',
    (dbo.SEM_AGENT.FREE_MEM/1073741824) as 'Free Memory (GB)', (dbo.SEM_COMPUTER.MEMORY/1073741824) as 'Total Memory (GB)', 
    dbo.SEM_COMPUTER.OPERATION_SYSTEM,NAME, SEM_AGENT.MAJOR_VERSION
    FROM dbo.sem_computer, [dbo].[V_SEM_COMPUTER], dbo.IDENTITY_MAP, dbo.SEM_CLIENT, dbo.SEM_AGENT
    WHERE [dbo].[V_SEM_COMPUTER].COMPUTER_ID = SEM_COMPUTER.COMPUTER_ID
    AND dbo.SEM_CLIENT.GROUP_ID = IDENTITY_MAP.ID
    AND dbo.SEM_CLIENT.COMPUTER_ID = dbo.SEM_COMPUTER.COMPUTER_ID
    AND dbo.SEM_COMPUTER.COMPUTER_ID = dbo.SEM_AGENT.COMPUTER_ID
    AND [IP_ADDR1_TEXT] = '$k'"

    $cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)


    do{
    try{
        $rdr = $cmd.ExecuteReader()

        if ($rdr -eq $Null){
            write-host $k not found in database
        }
        # Read Computer Name, Computer ID, IP address, Domain, and Operating System from the Database into a multidimensional array

        while ($rdr.read()){
                $sql_output += ,@($rdr.GetValue(0),",", $rdr.GetValue(1), ",", $rdr.GetValue(2),",",  $rdr.GetValue(3), ",", $rdr.GetValue(4), ",", $rdr.GetValue(5),",",  $rdr.GetValue(6), ",", $rdr.GetValue(7), ",", $rdr.GetValue(8))
        }

        $transactionComplete = $true
    }
    catch{
        $transactionComplete = $false
    }
    }until ($transactionComplete)



    $conn.Close()    
}

Add-Content C:\PS\NOC_IP_Address_Statistics.csv "Computer Name,IP Address,Free Disk Space (GB),Total Disk Space (GB),Free Memory (GB),Total Memory(GB),Operating System,Group,SEP Version" 
foreach ($i in $sql_output){
    Add-Content C:\PS\NOC_IP_Address_Statistics.csv "$i"
}

2 个答案:

答案 0 :(得分:2)

这适合我。

if ($rdr.Read()) { 'Data Exists'; $rdr.GetValue(0); }
else { 'No Data Returned' }

答案 1 :(得分:0)

您要做的是检查值是否为DBNull。所以这对你有用:

if ($rdr -eq [System.DBNull]::Value){
     write-host $k not found in database
}