Hey guys,
We have a system that lets users register their card, and then puts those users into a SQL Table. We then want the users who registered within the last 24 hours (or since the script was last run) to be put into an XML file.
I have written a PowerShell script that runs in three segments to do this:
-
- Executes an SQL Query that compares 2 tables and gives the differences.
-
- Puts the differences/results into an XML file
-
- Runs another SQL Query that updates the 2nd SQL table so they are identical again.
Through my testing it works perfectly for what I want it to do, however I have no error catching. How would you suggest I try/catch any errors, such as not being able to access the SQL Server?
$query = "SQL Query here" $DBServer = "DBSERVER" $databasename = "DBNAME" $constring = "server=$DBServer;database=$databasename;trusted_connection=True" #Creates the SQL Data Adapter we will use to fill out the table with a $da.fill code later $DataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter ($query, $constring) #Creates the datatable that we are going to fill with both static data and the SQL Data $DataTable = New-Object System.Data.DataTable "Pass" $DataAdapter.Fill($DataTable) | Out-Null $DataTable.WriteXml("c:xmltop1.xml") #Add the new entries into the 2nd SQL table $2ndQuery = "2nd SQL Query here" $DBServer = "DBSERVER" $databasename = "DBNAME" $constring = "server=$DBServer;database=$databasename;trusted_connection=True" $connection = New-Object System.Data.SqlClient.SqlConnection $connection.ConnectionString = $conString $connection.Open() $command = $connection.CreateCommand() $command.CommandText = $2ndQuery $result = $command.ExecuteReader() $connection.Close()
submitted by /u/mediaocrity23
[link] [comments]
The post PowerShell SQL Connection/Query error catching appeared first on How to Code .NET.