Connecting to SQL Server from Powershell to retrieve data

Posted on 2011-04-22
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

Question by:YZlat
    LVL 16

    Accepted Solution


    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] 
    $SqlCmd = New-Object Data.SqlClient.SqlCommand($SqlCommandText, $SqlConnection)
    $Reader = $SqlCmd.ExecuteReader()
    while ($Reader.Read())
      write-host $Reader["Field1"].ToString()

    Open in new window

    LVL 35

    Author Comment

    Let me try that.

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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Suggested Solutions

    The article will show you how you can maintain a simple logfile of all Startup and Shutdown events on Windows servers and desktops with PowerShell. The script can be easily adapted into doing more like gracefully silencing/updating your monitoring s…
    How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…

    761 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

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now