My First Powershell Script

Hello there, As a DBA, you must do numerous checks on your servers on a daily basis. It could involve things like monitoring disk space, running a health check, checking the status of services, and other minor details.
Instead of logging into each server to acquire the details, don’t you think you should have some type of automation script to get those details for you, and if you can execute them on a regular basis via task scheduler or a job on a daily basis, it will help you a lot?
And this is where Powershell automation comes in helpful.

So here is your first Powershell script to connect to your server and get the data.

<#
   My First Powershell script
#>

#Assign a server name to the $server variable
$server = 'servername'

#Create a connection to the server
$connectionstring = "Data Source"="+"$server"+";Initial Catalog=master;Integrated Security=SSPI;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionstring

#Create a command
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = "Select * FROM sys.databases"

#Assign the command to the connection
$command.Connection = #Connection

#Create an adapter
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command

#Create your dataset and fill the result
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-csv "C:\temp\output.csv"  #Output your data to a csv file
#or
$DataSet.Tables[0] | Out-GridView   #another way to see the output

This script will return the database names from the SQL server. Just change the select query and you will get the desired output from the server.

This is how the script looks in the editor.

Hope you find it useful. Please provide your feedback in the comments.
Thank You! Happy Learning!

In the next post we will see how to get data from multiple servers.
Powershell script for multiple servers

Leave a comment