Read the SQL Server Error Log with PowerShell

This script uses a native client call, so you can use it on any machine that has PowerShell installed along with the SQL Server client software. As always, only run this script on a test system until you understand what it does, and of course you'll need to change the server name in the connection string below:

# Connect and run a command using SQL Native Client, Returns a recordset
# Create and open a database connection
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "server=(local);database=master;Integrated Security=sspi"
#Create a command object
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = "xp_ReadErrorLog"
#Execute the Command
$sqlReader = $sqlCommand.ExecuteReader()
#Parse the records, read all three columns returned
while ($sqlReader.Read()) { $sqlReader[0], $sqlReader[1], $sqlReader[2] }
# Close the database connection

Comments (3)
  1. cmille19 says:

    You can also use SMO:

    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") > $null

    $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") ‘Z002SQLEXPRESS’


  2. BuckWoody says:

    That is awesome. Thanks for the post!

  3. BuckWoody says:

    Also – if you have the PowerShell Provider for SQL Server 2008, this works (you need to know the server name and instance name you want to read – mine is called BWOODY1 and SQL2K8)

    $MyServer = get-item SQLSERVER:SQLBWOODY1SQL2K8


Comments are closed.

Skip to main content