Search This Blog

Sunday, August 27, 2017

Insert Data in SQL Table Using PowerShell

function DataSuccessErrorFunction ([Data.SqlClient.SqlConnection] $OpenSQLConnection) {
     $sqlCommand = New-Object System.Data.SqlClient.SqlCommand
    $sqlCommand.Connection = $sqlConnection
    # This SQL query will insert 1 row based on the parameters, and then will return the ID
    # field of the row that was inserted.
    $sqlCommand.CommandText ="INSERT INTO dbo.tblPowershellExecutionHistory (Domain,WindowsLoginID,PowerShellExcutionMessage) VALUES (NGO,NGO\shrawan','Successfully'); "
    $sqlCommand.ExecuteNonQuery()
# close connection
}
# Open SQL connection (you have to change these variables)
$DBServer = "NGOMan"
$DBName = "DB_NGO"
$Password = "NGO"
$UserID = "NGO"
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=$DBServer;Database=$DBName;User ID=$UserID;Password=$Password; Integrated Security=True;"
$sqlConnection.Open()
# Quit if the SQL connection didn't open properly.
if ($sqlConnection.State -ne [Data.ConnectionState]::Open) {
    "Connection to DB is not open."
    Exit
}
# Call the function that does the inserts.
DataSuccessErrorFunction ($sqlConnection)
# Close the connection.
if ($sqlConnection.State -eq [Data.ConnectionState]::Open) {
    $sqlConnection.Close()
}

No comments:

Post a Comment