E
E
Evgeny Kotov2021-02-23 17:57:59
SQL
Evgeny Kotov, 2021-02-23 17:57:59

How to properly insert data into SQL table from Powershell?

Good day.
How to correctly insert data into a table using Powershell

Code example:

function Invoke-SQL {
    Param(
        [string]$DataSource,
        [string]$Database,
        [string]$SqlCommand,
        [string]$User,
        [string]$Password
    )
    if (($User) -and ($Password)) {
        $connectionString = "Data Source=$dataSource;User ID=$User;Password=$Password;Initial Catalog=$Database"
    } else { 
        $connectionString = "Data Source=$dataSource; " + "Integrated Security=SSPI; " + "Initial Catalog=$database"
     }
    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $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
}
$date = Get-Date -Format MM/dd/yyyy
$zeit = Get-Date -Format HH:mm

echo $date , $zeit , $Env:USERNAME

Invoke-SQL -dataSource PC-EKOTOV\SQLEXPRESS -database Login -sqlCommand "INSERT INTO login VALUES ($Env:USERNAME, $date, $zeit, '0');"


On execution, a date conversion error occurs.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxKozlov, 2021-02-24
@MaxKozlov

the simplest is to use $command.Parameter, rather than invent your own sql injections.
And, if you're doing an INSERT, don't bother with an Adapter, it's for a SELECT. You need
executenonquery

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question