Skip to content

31. SQL queries

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

Item Description
$ServerInstance Here we have to mention the instance in which the database is present
$Database Here we have to mention the database in which the table is present
$Query Here we have to the query which you we want to execute in SQL
$Username & $Password UserName and Password which have access in database

31.1: SQLExample

For querying all the data from table MachineName we can use the command like below one.

1
2
3
4
5
6
7
$Query="Select * from MachineName"
$Inst="ServerInstance"
$DbName="DatabaseName
$UID="User ID"
$Password="Password"

Invoke-Sqlcmd2 -Serverinstance $Inst - Database $DBName -query $Query -Username $UID - Password $Password

31.2: SQLQuery

For querying all the data from table MachineName we can use the command like below one.

1
2
3
4
5
6
7
$Query="Select * from MachineName"
$Inst="ServerInstance"
$DbName="DatabaseName
$UID="User ID"
$Password="Password"

Invoke-Sqlcmd2 -Serverinstance $Inst - Database $DBName -query $Query -Username $UID - Password $Password