【问题标题】:Determine the number of records in an OLEDB Recordset确定 OLEDB 记录集中的记录数
【发布时间】:2022-01-10 19:21:58
【问题描述】:

我窃取了以下代码,允许我通过 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

【问题讨论】:

  • 检查你的$dtRows.Count == 0
  • 哈!!非常感谢

标签: powershell csv sql-query-store


【解决方案1】:

Dai's helpful 注释之后,您可以使用-not 逻辑运算符作为Rows.Count -eq 0 的另一种替代方法来检查PowerShell 语法:

$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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 2010-09-25
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多