?
Solved

Connecting to SQL Server from Powershell to retrieve data

Posted on 2011-04-22
2
Medium Priority
?
506 Views
Last Modified: 2012-05-11
I need a powershell function that takes one parameter, connects to SQL Server database and retrieves data based on input parameter

SELECT Field1 FROm Table1 WHERE Field2=@parameter

0
Comment
Question by:YZlat
2 Comments
 
LVL 16

Accepted Solution

by:
Bryan Butler earned 2000 total points
ID: 35447535

How about:

$SqlConnection = New-Object system.Data.SqlClient.SqlConnection 
$SqlConnection.ConnectionString = "Server=$SqlServer;Database=$SqlDB;Integrated Security=True"


$SqlCommandText = "SELECT Field1 FROm Table1 WHERE Field2=" + $args[0] 
$SqlConnection.Open()
$SqlCmd = New-Object Data.SqlClient.SqlCommand($SqlCommandText, $SqlConnection)
$Reader = $SqlCmd.ExecuteReader()

while ($Reader.Read())
{
  write-host $Reader["Field1"].ToString()
}

Open in new window

0
 
LVL 35

Author Comment

by:YZlat
ID: 35447574
Let me try that.

Is there a way to put it all into a function and then call that function from my script?
0

Featured Post

Free recovery tool for Microsoft Active Directory

Veeam Explorer for Microsoft Active Directory provides fast and reliable object-level recovery for Active Directory from a single-pass, agentless backup or storage snapshot — without the need to restore an entire virtual machine or use third-party tools.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
Transferring FSMO roles is done when an admin wants to split roles between certain Domain Controllers or the Domain Controller holding the Roles has been forcefully demoted using dcpromo / forceremoval
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Loops Section Overview

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question