Create SQL Database for Monitor Data
1 min readAfter my last post, now I have figured out the step on how to create the database we need to house the Computer monitor data. The code Below logs into a SQL instance based on the information you input in the first two sections and creates the Database you need based off of our prior script
# Set your SQL Server instance and database name
$SQLServerInstance = "DBSERVER\InstanceName"
$DatabaseName = "MonitorDB"
# Set your credentials (replace 'username' and 'password' with your own)
$Username = "dbuser"
$Password = "dbpassword"
# Load the required assembly for SQL Server
# Create a new SQL connection
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServerInstance;Database=master;User Id=$Username;Password=$Password;"
# Open the SQL connection
$SqlConnection.Open()
# Create the database
$CreateDatabaseCommand = New-Object System.Data.SqlClient.SqlCommand
$CreateDatabaseCommand.Connection = $SqlConnection
$CreateDatabaseCommand.CommandText = "CREATE DATABASE [$DatabaseName];"
$CreateDatabaseCommand.ExecuteNonQuery()
# Close and reopen the connection with the new database
$SqlConnection.Close()
$SqlConnection.ConnectionString = "Server=$SQLServerInstance;Database=$DatabaseName;User Id=$Username;Password=$Password;"
$SqlConnection.Open()
# Create the table for the monitor data
$CreateTableCommand = New-Object System.Data.SqlClient.SqlCommand
$CreateTableCommand.Connection = $SqlConnection
$CreateTableCommand.CommandText = @"
CREATE TABLE MonitorData (
ID INT IDENTITY(1,1) PRIMARY KEY,
ComputerName NVARCHAR(255) NOT NULL,
ManufacturerName NVARCHAR(5) NOT NULL,
SerialNumber NVARCHAR(50) NOT NULL,
MonitorSize INT NOT NULL
);
"@
$CreateTableCommand.ExecuteNonQuery()
# Close the SQL connection
$SqlConnection.Close()
1 thought on “Create SQL Database for Monitor Data”