Powershell use Connection String to query Database and write to Excel

Right now I have a powershell script that uses ODBC to query SQL Server 2008 / 2012 database and write to EXCEL
$excel = New-Object -Com Excel.Application
$excel.Visible = $True
$wb = $Excel.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws.name = "GUP Download Activity"
$qt = $ws.QueryTables.Add("ODBC;DSN=$DSN;UID=$username;PWD=$password", $ws.Range("A1"), $SQL_Statement)
if ($qt.Refresh()){
$ws.Activate()
$ws.Select()
$excel.Rows.Item(1).HorizontalAlignment = $xlCenter
$excel.Rows.Item(1).VerticalAlignment = $xlTop
$excel.Rows.Item("1:1").Font.Name = "Calibri"
$excel.Rows.Item("1:1").Font.Size = 11
$excel.Rows.Item("1:1").Font.Bold = $true
$filename = "D:\Script\Reports\Status_$a.xlsx"
if (test-path $filename ) { rm $filename }
$wb.SaveAs($filename, $xlOpenXMLWorkbook) #save as an XML Workbook (xslx)
$wb.Saved = $True #flag it as being saved
$wb.Close() #close the document
$Excel.Quit() #and the instance of Excel
$wb = $Null #set all variables that point to Excel objects to null
$ws = $Null #makes sure Excel deflates
$Excel=$Null #let the air out
I would like to use connection string to query the database and write results to EXCEL, i.e.
$SQL_Statement = "SELECT ..."
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=10.10.10.10;Initial Catalog=mydatabase;User Id=$username;Password=$password;"
$conn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand($SQL_Statement,$conn)
do{
try{
$rdr = $cmd.ExecuteReader()
while ($rdr.read()){
$sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1))
$transactionComplete = $true
catch{
$transactionComplete = $false
}until ($transactionComplete)
$conn.Close()
How would I read the columns and data for $sql_output into an EXCEL worksheet. Where do I find these tutorials?

Hi Q.P.Waverly,
If you mean to export the data in $sql_output to excel document, please try to format the output with psobject:
$sql_output=@()
do{
try{
$rdr = $cmd.ExecuteReader()
while ($rdr.read()){
$sql_output+=New-Object PSObject -Property @{data1 = $rdr.GetValue(0);data2 =$rdr.GetValue(1)}
$transactionComplete = $true
catch{
$transactionComplete = $false
}until ($transactionComplete)
$conn.Close()
Then please try to use the cmdlet "Export-Csv" to export the data to excel like:
$sql_output | Export-Csv d:\data.csv
Or you can export to worksheet like:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$workbook = $excel.Workbooks.Add()
$sheet = $workbook.ActiveSheet
$counter = 0
$sql_output | ForEach-Object {
$counter++
$sheet.cells.Item($counter,1) = $_.data1$sheet.cells.Item($counter,2) = $_.data2}
Refer to:
PowerShell and Excel: Fast, Safe, and Reliable
If there is anything else regarding this issue, please feel free to post back.
Best Regards,
Anna Wang

Similar Messages

  • Connection String to Local Database Problem

    I just copied a database on the development server which I am not owner of, but I have rights to the database. I copied it to my local server. Now I need to connect to the local database and I don't know how.
    Dim MM_cnnName_STRING
    MM_cnnName_STRING = "Provider=SQLOLEDB.1;Password=xxx;Persist Security Info=True;User ID=xxx;Initial Catalog=DBName;Data Source=DevComputerName"
    The above is what I used to connect to the development server. How can I figure out the string for my local MS SQL Server

    Now I have this error once I try to bring up a page that calls the db
    Microsoft OLE DB Provider for SQL Server error  '80004005'
    Login failed. The login is from an untrusted domain  and cannot be used with Windows authentication.
    /CourseList.asp, line  9

  • Unable to connect using connect string in linus using sys user in Linux

    Hi,
    I am facing problem in using connect string while connecting as sys user in Linux OS
    For example:
    When I am connecting as
    sys/sysoracle as sysdba its getting connected.
    But when I am providing the connect string such as sys/sysoracle@TEST as sysdba its showing with error as:
    ORA-12505: TNS :listener does not currently know of SID in connect descriptor
    Any help will be benefitial for me
    Thanks and Regards

    >
    ORA-12505:
    TNS:listener does not currently know of SID given in connect descriptor
    Cause:     The listener received a request to establish a connection to a database or other service. The connect descriptor received by the listener specified a SID for an instance (usually a database instance) that either has not yet dynamically registered with the listener or has not been statically configured for the listener. This may be a temporary condition such as after the listener has started, but before the database instance has registered with the listener.
    Action:     
    - Wait a moment and try to connect a second time.
    - Check which instances are currently known by the listener by executing: lsnrctl services <listener name>
    - Check that the SID parameter in the connect descriptor specifies an instance known by the listener.
    - Check for an event in the listener.log file.>
    So are you sure that TEST is a right connection string that you are using and is rightly configured?
    HTH
    Aman....

  • Is "sp_purge_data" available only to datawarehouses or can it be used with both a normal database and Azure storage as well ?

    Is "sp_purge_data" available only to datawarehouses or can it be used with both a normal database  and Azure storage as well ?

    Thank you for the reply Qiuyun , the article was really helpful!
    I do have couple of other questions for you :
    How do we execute our SQL queries on Windows Azure tables and create horizontal partitions ? (I know that we have our SQL Server management Studio to execute normal queries on a SQL database , do we have a similar platform for Azure or do we have to get a local
    copy of the database to execute our queries and the  publish everything back to Azure)? I am looking to partition data on one of our databases and would like to know if it can be done in Azure directly or if we have to bring a local copy down ,write the
    partition function and
    and partition scheme or create a partition key and a row key - do the needful and publish it back to Azure?
    Also, how do I create a partition key and row key in Windows Azure?
    I am in the process of designing data archiving strategy for my team and would like to know more about the questions I just mentioned.
    Hoping to hear back from you soon.
    Thanks in advance for all the help!
    -Lalitha.

  • How to retrieve characters like '£' from the database and write to xml file

    Hi ,
    I have a requirement to retrieve the data from database and write to files in XML format.
    I am able to do so successfuly by using XMLElement tag and writing to file through UTL_File package.
    All characters like <&@^ get converted properly, but when it comes to multibyte chars like '£', they are not able to get converted as it is.
    Can somebody please advise me how to go ahead.
    Regards

    Thanks odie.
    The nls_charset for my database is WE8ISO8859P1 and database version is Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi.
    The data (with pound sign) is sitting in one of the columns of the table and when i query it directly, I am able to view it properly.
    However when I use the below code to retrieve in XML format and print it to file, it gets changed. This file is also passed to one of the application GUI where this XML gets processsed and it is not visible properly.
    below id the sample abstract of code I am using.
    Declare
    l_file UTL_FILE.FILE_TYPE;
    l_clob CLOB;
    l_buffer VARCHAR2(32767);
    l_amount BINARY_INTEGER := 32767;
    l_pos INTEGER := 1;
    Begin
    SELECT XMLElement("case",
    XMLElement("comments",
    XMLElement("comment",
    XMLElement("comments",a.COMMENTS)
    ).getClobVal() val1 into l_clob
    FROM TO_COMMENTS a
    l_file :=
    UTL_FILE.fopen (XMLDIR,
    test.xml,
    'w',
    32767);
    LOOP
    DBMS_LOB.read (l_clob,
    l_amount,
    l_pos,
    l_buffer);
    UTL_FILE.put_line (l_file, l_buffer);
    l_pos := l_pos + l_amount;
    END LOOP;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.NEW_LINE('Reached end of file');
    END;
    The comments column given contains the character like pound.
    And once the file is generated and i see using the vi editor, the char is not viewable properly like £
    And when the same is passed to GUI application to be processed, its not viewable propely in GUI from IE as well like �.

  • Connect to database and write query statements in the *****Impl.java??

    http://www.oracle.com/technology/pub/articles/vohra-jdev-xmlpub.html
    I used the above link to create XML's and from there a formatted report of data from the database. I accomplish this by connecting to the database inside the XMLPublisher.java file. I also have my query hard-coded inside the DataTemplate.xml to extract the info from the database. This limits my ability on what the user can accomplish with the system.
    Is it possible to run my reports based on an iterator within Jdeveloper, as opposed to having to manually enter the query and connect to the database within the XMLPublisher.java file and the template.xml? ..Possibly connecting to the database and and writing queries in the *****impl.java?
    Thanks.

    Rather than inventing your own demi-donkeyed solution I recommend you consider using Oracle's Fine-Grained Auditing which does precisely this.
    Cheers, APC

  • How get connection string of default database of CreateUserWizard control

    hi,
    i am creating website in which I add create user wizard control, I want to restrict user to use one email id only for one time,
    but after creating and testing,I get that it allow same email id more than one time, for that I search lot and get this on msdn library,  they show that to change config file
    <configuration>
    <connectionStrings>
    <add name="MySqlConnection" connectionString="Data
    Source=MySqlServer;Initial Catalog=aspnetdb;Integrated
    Security=SSPI;" />
    </connectionStrings>
    <system.web>
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
    <providers>
    <clear />
    <add
    name="SqlProvider"
    type="System.Web.Security.SqlMembershipProvider"
    connectionStringName="MySqlConnection"
    applicationName="MyApplication"
    enablePasswordRetrieval="false"
    enablePasswordReset="true"
    requiresQuestionAndAnswer="true"
    requiresUniqueEmail="true"
    passwordFormat="Hashed" />
    </providers>
    </membership>
    </system.web>
    </configuration>
    but,I didn't figure out any database in vs2010 that store data of create user wizard, mean i don't know how to access it in from vs2010
    site is working fine, it add new user , allow me login, but where the database???
    I want connection string of it's
    mandar26

    Hello Mandar26,
    The question should be asked on http://forums.asp.net/ Please reopen a new case there for help.
    Regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to use muti-thread to query database?

    if i want to use two or more threads to query a database for data,what should i do?anybody know?

    Hi,
    I have 2 suggestions to help you do this.
    First, the Berkeley DB XML Transaction Guide uses has a multi-threaded application and several discussions about DB_THREAD.
    For more information see:
    http://www.oracle.com/technology/documentation/berkeley-db/xml/gsg_xml_txn/cxx/introduction.html#multithread-intro
    The following section should also be useful:
    http://www.oracle.com/technology/documentation/berkeley-db/xml/gsg_xml_txn/cxx/txnconcurrency.html#concurrenthandles
    If after reading about this and trying to implement you have a specific question, please post it here.
    You might also take a look in the Berkeley DB examples, TxnGuide.cpp which is a multi-threaded application.
    Ron

  • Can we connect Mapview to multidimensional database and retrieve data

    I have zero knowledge on MapViewer and hence I am curious to know, if we can connect MapViewer to multidimensional database(Like Essbase etc...) and retrieve data from them ???

    Currently, MapViewer needs a conection to an Oracle Database where MapViewer metadata is stored. You may be able to access external spatial data if there is a java implementation of an interface to access external native data. MapViewer provides a spatial provider implementation for shapefiles. For other data, including from external databases, you may be able to access them if a java class implements the spatial provider interface class. Mapviewer Users Guide has some notes about implementing a external spatial provider.

  • Chnage connection string after moving database

    re-configure database after moving

    Hi marky101,
    I would suggest you elaborate your scenario/environment/issue with more detail, so that the community members will help you in a effecient manner.
    If you want to dynamic change the data connection string in your C# application, please take a look at the following article:
    Dynamic Connection String:
    http://www.codeproject.com/Articles/755380/Dynamic-Connection-String
    If you have any concern regarding move a database from one server to another server, please see the article below:
    Move a database from one server to another server in SQL Server 2008:
    http://blogs.msdn.com/b/sreekarm/archive/2009/09/11/move-a-database-from-one-server-to-another-server-in-sql-server-2008.aspx
    Elvis Long
    TechNet Community Support

  • Find a string in a file and write a new text after it

    hi
    i try to search a string in a small text file. after this position I should write a new text (it is not the end of the text, it could be somewhere between).
    I tried to solve this with the StrginTokenizer, but it does not work properly, any other ideas how to solve this?
    thanks for your comments
    steinfresser

    To insert text into the middle of a file you use the process that has been used since the first text editor was invented over 50 years ago:
    1. Read the text from the file up to the insert point, and write it to a new file.
    2. Write the inserted text to the new file.
    3. Read the rest of the text from the file, and write it to the new file.
    4. Delete the file.
    5. Rename the new file.

  • Using cfhttp to read a page and write its contents to a file.

    Hi,
    I am trying to get a feed of my ebay store listings to load
    into froogle. Unfortunately, ebay provides the feed as a website
    not a file and froogle (via GoogleBase) needs the file to be
    submitted as an XML file.
    Is there a way to use something like cfhttp to load up the
    page where the feed is located, scan the page and write it's
    contents into an XML file that I can then load up to GoogleBase???
    thanks for the help.

    ignore me now.... I answered my own question a short while
    ago.
    for anyone who cares....
    I used CFHTTP to get the page and then used a cffile to write
    the #cfhttp.filecontent# into the new file!

  • What is the best way to read, process, and write an Excel File Server side...SQL Server Agent Job

    So I was using dynamic Excel commands to open and save as using...
    Microsoft.Office.Interop.Excel.Application
    and
     workbook.SaveAs(StringDestinationFile, XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    which worked all fine and dandy client side. Then when I attempted to create a SQL Server Agent Job, this failed as a result of SQL Server side not being able to execute dynamic Excel commands.
    So do I need to therefore try and do this function via Microsoft.ACE.OLEDB.12.0 commands? And where can I find the commands and syntax to open and save as? I have to Open a .xlsx file, save it as a .xls file, and then open this newly created .xls file and
    then save it as a .csv file.
    Thanks for your review and am hopeful for a reply.
    ITBobbyP85

    I think you might be over complicating things.
    You can use SSIS with Excel Source/Destination connections to read in, or output to an excel sheet/file.

  • How to connect oracle database with mvc3 either can use connection string or dbcontext??? please help me

    hi can anyone please help me??

    Are you using the Oracle ODBC driver? If so, which version?
    Are you writing your own VB application? What API are you using-- ADO? Can you post the code that's making a connection and the exact text of the error message?
    Justin

  • Query database and return result set to cells.

    hello all i have vsto solution im building im trying to put together a generic query text box for my end user the only problem is that it appears to be that with oracle data access when you do a query you must pass all the values to a variable.
    Sub Orcl()
            Dim oradb As String = "Data Source=(DESCRIPTION=(ADDRESS_LIST=" _
                       + "(ADDRESS=(PROTOCOL=TCP)(HOST=xxx)(PORT=1521)))" _
                       + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=xxx)));" _
                       + "User Id=xx;Password=xx;"
             Dim conn As New Oracle.DataAccess.Client.OracleConnection(oradb) ' Visual Basic
            conn.Open()
            Query = select * from fabinvh
            Dim cmd As New Oracle.DataAccess.Client.OracleCommand
            cmd = conn.CreateCommand()
            cmd.Connection = conn
            cmd.CommandText = Query
            Dim dr As Oracle.DataAccess.Client.OracleDataReader = cmd.ExecuteReader()
            While dr.Read()
                Globals.ThisAddIn.Application.ActiveCell.Value = (dr.Item(1))''' HOW DO I CHANGE HERE TO JUST BRING IN ALL THE COLUMNS AND HEADERS?
                Globals.ThisAddIn.Application.ActiveCell.Offset(1, 0).Select()
            End While
            dr.Dispose()
            cmd.Dispose()
            conn.Dispose()
        End Subthanks in advance im able to do this with oo4o rather easily but I'm tryint go learn more of the odp.net oracle data access and learning is pretty slow right now.

    ok I think im getting closer to my answer i believe i need to use the
    GetValues. property. does anyone have an example on how to use this i keep getting errors when i try it.

Maybe you are looking for

  • Initial Order in automatic PO Confirmation from SO

    Hi, I define the purchase price of items in the sales order (in an UDF). Then I Turn on the 'Purchase Orders' checkbox. After adding the order, I have to fill the 'Purchase Order Confirmation' form. I would like to populate the 'Unit Price' field wit

  • SXMB_MONI shows error in Java Proxy (Inbound)

    Hi All, My scenario is FTP->XI->Java Proxy->FTP I have configured the JPR Adapter and registered it correctly. But in SXMB_MONI, I am getting the error in JPR Adapter(Response) stating that, <u><b>Error when receiving by HTTP (error code: 108, error

  • How do we create a vendor using portal?

    how do we create a vendor using portal. creation process needs to trigger workflow. Sonali

  • Do you guys know this???

    I see this effect in very many music videos and it makes them kinda look cool and professional. This light streaks usually, red, pink, purple used for transitioning between one cut to another. I know its not lens flare. Please check out this music vi

  • Garageband 10.0.1 Sampler

    Is there a sampler on board 10.0.1?  I can't fins it, and this is a MAJOR loss to me if it isn't there.