Add Entries into SQL Database

email me

Eventually, you’re going to want to send information from clients (create records) to a database. There are many ways to do this, but using PowerShell is the most modern way.

This script accesses the ‘Test’ DB, and creates a record with the client computer name and timestamp.

[String]$dbname = "Test";

$computername = $env:COMPUTERNAME
$timeformat='MM-dd-yyyy hh:mm:ss tt'
$time = (Get-Date).ToString($timeformat)

# Open Connection with Windows authentication to local SQLSERVER.
$con = New-Object Data.SqlClient.SqlConnection;
$con.ConnectionString = "Data Source=.;Initial Catalog=Test;Integrated Security=True;";
$con.Open();

# Create the record.
$sql = "INSERT INTO Inventory.ComputerInfo ([ComputerName],[AcquiredDate])
VALUES('{0}','{1}')" -f
$computername,$time
$cmd = New-Object Data.SqlClient.SqlCommand $sql, $con;
$cmd.ExecuteNonQuery();

# Write-Host "Computer Name: $computername";
# Write-Host "Time: $time";
# Write-Host "SQL Command: $sql";
Write-Host "Record has been created";

# Close and Clear all objects.
$cmd.Dispose();
$con.Close();
$con.Dispose();