确定OLEDB记录集中的记录数



我窃取了以下代码,该代码允许我通过SQL查询来查询csv文件。代码可靠地输出了一个很好的表。最终,如果查询结果为零记录,我想执行一个操作。

我该怎么做呢?

$firstRowColumnNames = "Yes"
$delimiter = ","
$provider = 'Microsoft.ACE.OLEDB.16.0' 
$connstring = "Provider=$provider;Data Source=$(Split-Path $csv);Extended Properties='text;HDR=$firstRowColumnNames;';"
$tablename = (Split-Path $csv -leaf).Replace(".","#")
$sql = "SELECT * from [$tablename] Where sSamAccountName='acco'"
$sql
$conn = New-Object System.Data.OleDb.OleDbconnection
$conn.ConnectionString = $connstring
$conn.Open()
$cmd = New-Object System.Data.OleDB.OleDBCommand
$cmd.Connection = $conn
$cmd.CommandText = $sql
# Load into datatable
$dt = New-Object System.Data.DataTable
$dt.Load($cmd.ExecuteReader("CloseConnection"))
#Clean up
$cmd.dispose | Out-Null; $conn.dispose | Out-Null
#Output results
$dt | Format-Table -AutoSize

根据Dai的有用评论,在PowerShell语法上,您可以使用-not逻辑运算符作为Rows.Count -eq 0:的另一种替代方法来检查这一点

$dt = [System.Data.DataTable]::new()
$dt.Columns.AddRange(@('col1','col2'))
# DataTable only has 2 columns defined but now Rows
-not $dt.Rows.Count  # -not 0 or -not $null -> $true // [int]$null = 0
[bool]$dt.Rows.Count # [bool]$null or [bool]0 -> $false
# Add a new Row to the DataTable
$row = $dt.NewRow()
$row['col1'] = 'ExampleVal1'
$row['col2'] = 'ExampleVal2'
$dt.Rows.Add($row)
-not $dt.Rows.Count  # not 0 or not null when negated -> $false
[bool]$dt.Rows.Count # not 0 or not null in boolean expression -> $true
$dt.Dispose()

最新更新