Home > Enterprise >  Powershell SQL Query - Problem with a property "Site"
Powershell SQL Query - Problem with a property "Site"

Time:01-26

I'm a beginner in powershell and SQL Query. I figured out how to make a Query and i'm getting some results but i ran into a problem and don't know how to manage it.

My Code:

$dataSource = "MyBdServer"
$database = "DabaseName"
$connectionString = "Data Source=$dataSource; "   "Integrated Security=SSPI; "   "Initial Catalog=$database"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$sqlCommand = "select Site, Pavillon, Floor, Localisation, Description from [DabaseName].dbo.Local_C where Location_ID In ( '6096B3F168C546BE84A7A98C8210E947')"
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$dataSet.Tables

Output

Site         : NCH
Pavillon     : D
Floor        : Level S3
Localisation : D.S3.5113
Description  : CONSULT./ENTREVUE

The problem: when i'm trying to get the value by properties for site ($DataSet.Tables.Site) value is always empty, it works well with Pavillon, Floor, Localisation and Description. I think it's because the Object System.Data.Dataset has a property with that name by default. I'm trying to find a way to use this value.

CodePudding user response:

DataColumn has a Site property which is why you're unable to reference the values of the Site column. There are two easy alternatives, the easiest one is to reference the .Table property of your DataTable and then the .Site property and the other alternative is to use the .ToTable(..) method from DataView.

$columns = @(
    'Site'
    'Pavillon'
    'Floor'
    'Localisation'
    'Description'
)

$dtt = [System.Data.DataTable]::new()
$columns | ForEach-Object{
    $dtt.Columns.Add([System.Data.DataColumn]::new($_))
}
$row = $dtt.NewRow()
$row.Site         = 'NCH'
$row.Pavillon     = 'D'
$row.Floor        = 'Level S3'
$row.Localisation = 'D.S3.5113'
$row.Description  = 'CONSULT./ENTREVUE'
$dtt.Rows.Add($row)

$dtt.Site       # => Doesn't work
$dtt.Table.Site # => Works

$dv = [System.Data.DataView]::new($dtt)
$dv.ToTable($true, 'Site') # => Works
  •  Tags:  
  • Related