使用Powershell的SQL查询 - 返回值不匹配

时间:2013-06-03 07:51:06

标签: sql sql-server powershell powershell-v2.0 powershell-v3.0

所以我编写了一些代码来将输入表单作为文本文件并对我填充的另一个数据库运行一些sql检查:

$volOutput = gc C:\Users\<user>\Desktop\mutant.txt 

foreach ($m in $volOutput) { 

  $check = $m.split()[-1] | select -Unique

  foreach ($c in $check) {
    #$c - this lists all of them so the foreach is working...

    # Build the connection and search the db for $c names.
    $conn = New-Object System.Data.SqlClient.SqlConnection
    $conn.ConnectionString = "Server=(localdb)\mutex; Database=MutexObjects"
    $conn.Open()
    $db = $conn.CreateCommand()
    $db.CommandText = "select Names from Objects WHERE Names='$c'"
    $db.ExecuteScalar()
    $conn.Close()    

  } # Foreach Check

} # First foreach

我得到的返回值是:

PS C:\> B:\Programming\powershell\parse_vol.ps1
ZonesCounterMutex
ZoneAttributeCacheCounterMutex
ZonesCacheCounterMutex
ZoneAttributeCacheCounterMutex
ZonesLockedCacheCounterMutex
ZonesCounterMutex
ZoneAttributeCacheCounterMutex
ZonesCacheCounterMutex
ZoneAttributeCacheCounterMutex
ZonesLockedCacheCounterMutex

哪个是正确的,但它也缺少了很多。例如,如果我从SQL管理工作室中获取单个样本并运行查询,我得到:

我在每个列表中填写“test”一词作为.... test。

Select Names From Objects WHERE Names='test'

Names

test

但是我没有看到上面代码输出的测试。通过查询SQL管理工作室中的数据库,我手动验证了大约5或6个以上。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

将文件内容与数据库中的完整名称列表进行比较:

$filecontent = Get-Content "C:\Users\<user>\Desktop\mutant.txt" `
          | % { $_.split()[-1] } `
          | select -Unique

$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=(localdb)\mutex; Database=MutexObjects"
$conn.Open()
$dbwrite = $conn.CreateCommand()
$dbwrite.CommandText = "SELECT Names FROM Objects"

$reader = $dbwrite.ExecuteReader([System.Data.CommandBehavior]::CloseConnection)
$dbcontent = while ( $reader.Read() ) { $reader[0] }

$conn.Close()    

Compare-Object $filecontent $dbcontent

Compare-Object是否显示差异?