Output SELECT statement to CSV file

Can someone advise the best approach please
I'm trying to create a CSV file from the output of a SELECT statement in ApEx as a PL/SQL block. I initially thought the simplest approach would be to use SPOOL and then execute the SELECT startment but I think this is a SQLPlus command and can't be used in PL/SQL.
I then tried using the 'UTL_FILE.PUT' command which works for a single record but I'm not sure how to implement this where the SELECT returns multiple records.
DECLARE
fHandler UTL_FILE.FILE_TYPE;
v_DAT VARCHAR(20);
v_Handle VARCHAR2(20);
BEGIN
SELECT DATA INTO v_DAT FROM HIP_TEST;
v_Handle := CONCAT('HIP_',CONCAT(TO_CHAR(sysdate,'yyyymmddhhmi'),'.csv'));
fHandler := UTL_FILE.FOPEN('/nfsacademy/amp/live', v_Handle, 'w');
UTL_FILE.PUTF(fHandler, v_DAT);
UTL_FILE.FCLOSE(fHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, 'Invalid path. Create directory or set UTL_FILE_DIR.');
END;

Hi,
You can try this.
DECLARE
fHandler UTL_FILE.FILE_TYPE;
v_DAT VARCHAR(20);
v_Handle VARCHAR2(20);
BEGIN
v_Handle := CONCAT('HIP_',CONCAT(TO_CHAR(sysdate,'yyyymmddhhmi'),'.csv'));
fHandler := UTL_FILE.FOPEN('/nfsacademy/amp/live', v_Handle, 'w');
FOR I IN (SELECT DATA FROM HIP_TEST)
LOOP
     UTL_FILE.PUTF(fHandler, i.data);
END LOOP;
UTL_FILE.FCLOSE(fHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, 'Invalid path. Create directory or set UTL_FILE_DIR.');
END;** NOT TESTED **
Alternatively you can also use DBMS_OUTPUT.PUT_LINE.
Regards,
Avinash
Edited by: Avinash Tripathi on Nov 17, 2009 3:35 PM

Similar Messages

  • Output chinese character to CSV file in UNIX

    Hi
    I encountered ABAP dump whenever output chinese character to CSV file in UNIX in ECC6. Error show as
    "At the conversion of a text from codepage '4102' to codepage '1100':
    - a character was found that cannot be displayed in one of the two
    codepages;
    - or it was detected that this conversion is not supported"
    The program with coding of statement OPEN DATASET xxxxx FOR OUTPUT IN TEXT MODE  ENCODING NON-UNICODE. Reason to output to OPEN statement to non-unicode as users would like to open the csv file thru Excel directly. They do not wish to open the text file in Excel. Can Experts please share with me how to overcome the problem?
    Thanks
    Kang Ring

    May be you could give a try with the following code and check
    OPEN DATASET xxxxx FOR OUTPUT IN TEXT MODE ENCODING NON-UNICODE CODEPAGE '4103'.
    Vikranth

  • How to asssign output value in the CSV file for the specific header

    Hi,
    I am using OpenScript 9.10. The problem I am facing is that, to Write the Output value captured from the application, When i am trying to use the methods "Appen String to File" i am unable to write / assign the out put value below the specific header. Can any one please look into this and post the methods related to Write the output vaues in to the CSV files under specific headers.
    Thanks in Advance.
    Thanks.,
    Siva

    Hi Alex,
    Thanks for your reply.I need to write the output value under specified parameter name.
    for example after creating the sales order,the order number have to write in the CSV file under
    OrderNumber column.I tried with appendStringtofille() method,by using this able to write the value under
    first column.But i need to write output value under specified columnname(means Header name in the cSV
    file).can u please give a reply for the above problem.
    Note: In that Csv file i am taking the input vales and also need to write the output values under
    specified column(header)
    Thanks,
    Siva Thota.

  • How to call a SP with dynamic columns and output results into a .csv file via SSIS

    hi Folks, I have a challenging question here. I've created a SP called dbo.ResultsWithDynamicColumns and take one parameter of CONVERT(DATE,GETDATE()), the uniqueness of this SP is that the result does not have fixed columns as it's based on sales from previous
    days. For example, Previous day, customers have purchased 20 products but today , 30 products have been purchased.
    Right now, on SSMS, I am able to execute this SP when supplying  a parameter.  What I want to achieve here is to automate this process and send the result as a .csv file and SFTP to a server. 
    SFTP part is kinda easy as I can call WinSCP with proper script to handle it.  How to export the result of a dynamic SP to a .CSV file? 
    I've tried
    EXEC xp_cmdshell ' BCP " EXEC xxxx.[dbo].[ResultsWithDynamicColumns ]  @dateFrom = ''2014-01-21''"   queryout  "c:\path\xxxx.dat" -T -c'
    SSMS gives the following error as Error = [Microsoft][SQL Server Native Client 10.0]BCP host-files must contain at least one column
    any ideas?
    thanks
    Hui
    --Currently using Reporting Service 2000; Visual Studio .NET 2003; Visual Source Safe SSIS 2008 SSAS 2008, SVN --

    Hey Jakub, thanks and I did see the #temp table issue in our 2008R2.  I finally figured it out in a different way... I manage to modify this dynamic SP to output results into
    a physical table. This table will be dropped and recreated everytime when SP gets executed... After that, I used a SSIS pkg to output this table
    to a file destination which is .csv.  
     The downside is that if this table structure ever gets changed, this SSIS pkg will fail or not fully reflecting the whole table. However, this won't happen often
    and I can live with that at this moment. 
    Thanks
    --Currently using Reporting Service 2000; Visual Studio .NET 2003; Visual Source Safe SSIS 2008 SSAS 2008, SVN --

  • Unable to output data to a csv file

    hi,
    i need to out put some values to a csv file (the one that is mapped to it in the databank). i have used the function
    rswapp.setdatabankvalue "name", value
    where name is the variable name that is mapped to the field that should be updated by the script and value contain a string value that i want to export...
    somehow this code is not working properly.... :(
    can someone help me.......
    thanks in advance

    Hi Priyanshu,
    The function setDatabankValue will not write to the .csv file, but it will override the current databank. This would be useful if you had a function in VBA that you would like to use to replace a Databanked parameter. In order to output to the csv you will need to use file i/o functions.
    From online help the code below is the basic syntax where "newline" is what is going to be placed in test.txt
    newline would be replaced by the new variable that you want to output. Also, be sure that you reference EmpirixUtilities in your VBA. Hope this helps.
    Jim
    Private Sub RSWVBAPage_beforePlay()
    Dim m_util As EmpirixUtilities.FileIO
    Set m_util = New EmpirixUtilities.FileIO
    Dim resultb As Boolean
    Dim mstatus As String
    'write a line
    resultb = m_util.WriteToFile("c:\Test.txt", "newlineText", Append, mstatus)
    Call RSWApp.WriteToLog(CStr(resultb), "", mstatus)
    Set m_util = Nothing
    End Sub

  • Generating CSV file with column names and data from the MySQL with JAVA

    Hi all,
    Give small example on ...
    How can I add column names and data to a CSV from from MySQL.
    like
    example
    sequence_no, time_date, col_name, col_name
    123, 27-apr-2004, data, data
    234, 27-apr-2004, data, data
    Pls give small exeample on this.
    Thanks & Regards
    Rama Krishna

    Hello Rama Krishna,
    Check this code:
    Example below exports data from MySQL Select query to CSV file.
    testtable structure
    CREATE TABLE testtable
    (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    text varchar(45) NOT NULL,
    price integer not null);
    Application takes path of output file as an argument.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    public class automateExport {
        public static void main(String[] args) {
            DBase db = new DBase();
            Connection conn = db.connect(
                    "jdbc:mysql://localhost:3306/test","root","caspian");
            if (args.length != 1) {
                System.out.println(
                        "Usage: java automateExport [outputfile path] ");
                return;
            db.exportData(conn,args[0]);
    class DBase {
        public DBase() {
        public Connection connect(String db_connect_str,
                String db_userid, String db_password) {
            Connection conn;
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(db_connect_str,
                        db_userid, db_password);
            } catch(Exception e) {
                e.printStackTrace();
                conn = null;
            return conn;
        public void exportData(Connection conn,String filename) {
            Statement stmt;
            String query;
            try {
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                //For comma separated file
                query = "SELECT id,text,price into OUTFILE  '"+filename+
                        "' FIELDS TERMINATED BY ',' FROM testtable t";
                stmt.executeQuery(query);
            } catch(Exception e) {
                e.printStackTrace();
                stmt = null;
    Greetings,
    Praveen Gudapati

  • How to generate mutiple Results for multiple SQL SELECT statements

    I just downloaded SQL Developer 1.5 and play around with it.
    On a daily basis, I need run 4 different SELECT statements and dump the output of each SELECT into an CSV file and send to some users. In SQL Navigator, I can select all 4 SELECT statements and execute them at same time. Once all complete, I will see 4 tabs, each represent the output for each SELECT statement. Then I can export output from each tab into a CSV file.
    It seems that SQL Developer 1.5 still can't run mutiple SELECT statements and display the output of each statement into a separate "Results" tab so that I can export the data into multiple CSV files easily.
    Right now, I have to hightlight each SELECT statement and press F9, then export the output data into CSV.
    I wish I can execute 4 SELECT statements all in once on SQL Developer and get all the output data and export 4 times into 4 CSV files.
    Thanks!
    Kevin

    How about doing it as a set of tabs within the Resuls Tab?
    So you would have your Top row of tabs:
    Results, Script Output, Explain, AutoTrace, DBMS Output and OWA Output
    Then When you have the Results tab selected you could have a row of tabs beneath the Top row with one tab for each result set. Switching between result sets should switch which section of SQL is highlighted as the "Current SQL".
    A similar mechinism could be employed for each of the top level tabs where it makes sense to have multiple output tabs.
    A further refinement of this feature might be to allow the result tabs to be dockable within the parent tab so that multiple result tabs can be viewed simultaneously. This way 2 or more explain plans (for example) could be visually compared without requiring the code to exist in two separate code panes.

  • How to refer/store  a vaue from csv file in control file

    Hi,
    Consider the following control file script.
    Load data
    infile 'suv.csv'
         append      into table mast_equipmnet_test
    fields terminated by "," optionally enclosed by '"'     
    TRAILING NULLCOLS
    equipment_id,
    sub_vehicle_type,
    ebiz_carrier_no expression "(select ebiz_carrier_no from mast_carrier where carrier_id=?)",
    licence_no,
    equip_type,
    ebiz_appown_no,
    ebiz_equip_no sequence(1,1)
    here is my csv file
    CABNO,          SUBTYPE     CARRIER_ID               REG_NO,     VEHICLE_TYPE,          EBIZ_APPOWN_NO
    6954,          SUMO,          SWAMY,                         6954,          SUV,                    228
    9183,          SUMO,          SWAMY,                         9183,          SUV,                    228
    3173,          QUALIS,          SWAMY,                         3173,          SUV,                    228
    In my csv file i have carrier_ids which are string values in 3rd column.
    for every carrier_id ,the corresponding ebiz_carrier_no(numeric value) is stored in a master table called "mast_carrier".
    While loading the data i need to fetch the ebiz_carrier_no for each carrier_id from mast_carrier table .
    but here i got strucked in the where clause of select statement.
    I am not able to refer the carrier_id from csv file in where clause.
    can any body tell me how to refere a value from csv file in the select statement of control file script.
    cheers
    RRK

    Sorry..
    "EXPRESSION" is not needed..
    ebiz_carrier_no "(select ebiz_carrier_no
    from mast_carrier
    where carrier_id=:ebiz_carrier_no )",
    <br>
    <br>
    "Tested" as
    <br>
    load data
    infile *
    into table t truncate
    fields terminated by ','
    (id,
    name "(select ename from emp
                       where empno = :name)"
    begindata
    1,7900
    2,7902
    <br>
    QL> select * from t;
           ID NAME
            1 JAMES
            2 FORD                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to get sql query data and write into csv file?

    I am writing to seek help, in how can I create bat. script which can execute the following logic:
    connection to the database
    run sql query
    create CSV file
    output query data, into CSV file
    save the CSV file
    osql
    -S 84.18.111.111
    -U adw
    -P rem
    -i "c:\query.sql"
    send ""
    sed -e 's/,\s\+/,/g' MCI_04Dec2014.csv > localNoSpaces.csv
    -o "c:\MCI_04Dec2014.csv"
    This what i have so far, and I am little struggling with the logic after creating CSV file. I am unable to get the above script to work, please advice further, where I may be going wrong. 
    Can you create if statement logic within window's script, to check for null parameters or data feeds?
    Any hints would be most appreciated. 

    Thank you for your reply. 
    Apology for posting the code irrelevant to the forum, as I am still novice scripting user.  
    My goal is to create window's script which can compute the above logic and send the final output file (csv), to FTP folder. 
    Can this logic be implemented via bat. script, if so, is there a example or tutorial i could follow, in order to achieve my task. 
    Any help would be much appreciated. 

  • BI Publisher : SELECT statement in RTF template

    Hi Guys
    I have written a BI Publisher Report using XML file created from Oracle Reports(in Oracle Apps).
    Repors runs from Oracle Apps perfectly ok. Now I need to fetch some data from couple of tables and display on the Report.
    I am wondering whether I can directly code SELECT statement in RTF file rather than messing with Oracle Report(.rdf) file.
    Please advise.
    Thanks and Regards
    Vijay

    Hey Vijay,
    You cannot query in RTF using select :)..
    You have to mess/play with RDF to do it ;)
    Oh wait, did i say , we cannot in RTF, we can , but that is difficult approach to go with., keep this as an end of the world option.

  • Web.Show_document to open .csv file in Excel How??

    We have a utility built in our menu (mmb)
    It reads the screen output and creates a .CSV file on the server using text_io and then using Web.show_document displays the file on the client.
    The file opens in MS-EXCEL. It gives a standard Excel prompt for Open , Save or run.
    Now our application has moved to FMW 11gAS.
    The file creation is happening but the file is opening in HTML format.
    The excel prompt is not coming.
    Where is setting to be done to open the .CSV files in EXCEL

    In addition to what I already mentioned, your issue may be partially caused by these two bugs: 10186820 & 10191154
    Both have been fixed in 11.1.1.6, which was released last week. Information about the 11.1.1.6 patch set can be found in MyOracleSupport note 1364511.1
    The fix should also already be in 11.1.2.0

  • Select statement reults to a CSV file, refuses to run

    Hi,
    have this query that outputs to a CSV file, or at least it should.
    Any help resolving this will be greatfully recieved
    Thanks
    set feedback off
    set pages 0
    set lines 120
    spool /gtxappl/Stock_Mirroring/Results/pyfs_Demandstock_supply.csv
    select upper('item_id,shipnode_key,jda_demand')
    from dual;
    select a.item_id || ',' || b.shipnode_key || ',' || sum (b.quantity)
    from yfs_inventory_item a, yfs_inventory_demand b
    where b.demand_type = 'JDA_RSRV.ex'
    and b.inventory_item_key = a.inventory_item_key;
    group by a.item_id, b.Shipnode_KEY
    spool off

    Hi,
    sorry about that. Its running now, was using an older version of the script, this is not the correct one.
    Any idea as to how i could write a shell script so that an application called TWS can execute the SQL and be passed back a success or failure code, 0= success >0= error for a sript very similar to the one mentioned before hand?
    Thanks

  • Open CSV output in default CSV viewer without CSV file?

    I can run a SELECT statement, export the data to a CSV file, and start my CSV viewer (Excel in my case) to see the data. Is there a way to not have to save the CSV file and just have my default CSV viewer start up with the exported data in it?
    Mike

    For it to be added as an enhancement for the program, as I often would like to review the file output before being satisfied that it is correct. Not that I don't trust what the program would do, but I don't trust what I would do.

  • How to generate a second csv file with different report columns selected?

    Hi. Everybody:
    How to generate a second csv file with different report columns selected?
    The first csv file is easy (report attributes -> report export -> enable CSV output Yes). However, our users demand 2 csv files with different report columns selected to meet their different needs.
    (The users don't want to have one csv file with all report columns included. They just want to get whatever they need directly, no extra columns)
    Thank you for any help!
    MZ

    Hello,
    I'm doing it usually. Typically example would be in the report only the column "FIRST_NAME" and "LAST_NAME" displayed whereas
    in the csv exported with the UTL_FILE the complete address (street, housenumber, additions, zip, town, state ... ) is written, these things are needed e.g. the form letters.
    You do not need another page, just an additional button named e.g. "export_to_csv" on your report page.
    The csv export itself is handled from a plsql procedure "stored procedure" ( I like to have business logic outside of apex) which is invoked by pressing the button "export_to_csv". Of course the stored procedure can handle also parameters
    An example code would be something like
    PROCEDURE srn_brief_mitglieder (
         p_start_mg_nr IN NUMBER,
         p_ende_mg_nr IN NUMBER
    AS
    export_file          UTL_FILE.FILE_TYPE;
    l_line               VARCHAR2(20000);
    l_lfd               NUMBER;
    l_dateiname          VARCHAR2(100);
    l_datum               VARCHAR2(20);
    l_hilfe               VARCHAR2(20);
    CURSOR c1 IS
    SELECT
    MG_NR
    ,TO_CHAR(MG_BEITRITT,'dd.mm.yyyy') AS MG_BEITRITT ,TO_CHAR(MG_AUFNAHME,'dd.mm.yyyy') AS MG_AUFNAHME
    ,MG_ANREDE ,MG_TITEL ,MG_NACHNAME ,MG_VORNAME
    ,MG_STRASSE ,MG_HNR ,MG_ZUSATZ ,MG_PLZ ,MG_ORT
    FROM MITGLIEDER
    WHERE MG_NR >= p_start_mg_nr
    AND MG_NR <= p_ende_mg_nr
    --WHERE ROWNUM < 10
    ORDER BY MG_NR;
    BEGIN
    SELECT TO_CHAR(SYSDATE, 'yyyy_mm_dd' ) INTO l_datum FROM DUAL;
    SELECT TO_CHAR(SYSDATE, 'hh24miss' ) INTO l_hilfe FROM DUAL;
    l_datum := l_datum||'_'||l_hilfe;
    --DBMS_OUTPUT.PUT_LINE ( l_datum);
    l_dateiname := 'SRNBRIEF_MITGLIEDER_'||l_datum||'.CSV';
    --DBMS_OUTPUT.PUT_LINE ( l_dateiname);
    export_file := UTL_FILE.FOPEN('EXPORTDIR', l_dateiname, 'W');
    l_line := '';
    --HEADER
    l_line := '"NR"|"BEITRITT"|"AUFNAHME"|"ANREDE"|"TITEL"|"NACHNAME"|"VORNAME"';
    l_line := l_line||'|"STRASSE"|"HNR"|"ZUSATZ"|"PLZ"|"ORT"';
         UTL_FILE.PUT_LINE(export_file, l_line);
    FOR rec IN c1
    LOOP
         l_line :=  '"'||rec.MG_NR||'"';     
         l_line := l_line||'|"'||rec.MG_BEITRITT||'"|"' ||rec.MG_AUFNAHME||'"';
         l_line := l_line||'|"'||rec.MG_ANREDE||'"|"'||rec.MG_TITEL||'"|"'||rec.MG_NACHNAME||'"|"'||rec.MG_VORNAME||'"';     
         l_line := l_line||'|"'||rec.MG_STRASSE||'"|"'||rec.MG_HNR||'"|"'||rec.MG_ZUSATZ||'"|"'||rec.MG_PLZ||'"|"'||rec.MG_ORT||'"';          
    --     DBMS_OUTPUT.PUT_LINE (l_line);
    -- in datei schreiben
         UTL_FILE.PUT_LINE(export_file, l_line);
    END LOOP;
    UTL_FILE.FCLOSE(export_file);
    END srn_brief_mitglieder;Edited by: wucis on Nov 6, 2011 9:09 AM

  • Help with output to 2 CSV files

    I created a script to parse through AD and output a list of computers that have certain info in the description field and it is working (wouldn't mind some critique if things could be done a better/faster way).  Now, what I am trying to do is split
    the output into 2 CSV files based on what is in the $descwho variable.  But I am not sure where to start (not looking for someone to rewrite the script but point me in the right direction).  I have tried a couple things but so far I have not gotten
    anywhere.
    Function Get-ScriptDirectory {
    if($hostinvocation -ne $null) {
    Split-Path $hostinvocation.MyCommand.path
    } else {
    Split-Path $script:MyInvocation.MyCommand.Path
    #Variable that provides the location of the script
    [string]$ScriptDirectory = Get-ScriptDirectory
    Function Clean-OU {
    #clean OU removes FQDN/RootOU from the start and $computername from the end of the OU string
    Param (
    $OriginalOU,
    $computer
    $ouArray = $OriginalOU.split("/")
    $newOU = $null
    Foreach ($OU in $ouArray) {
    If (($ou -ne "FQDN") -and ($ou -ne "RootOU") -and ($ou -ne $computer)){
    If (!$newOu) {
    $newOU = ".../$ou"
    } Else {
    $newOU += "/$ou"
    return $newOU
    $path = "$ScriptDirectory\ad_report_2.csv" #path to where report is saved
    Get-ADComputer -Filter * -Properties Description,Enabled,MemberOf,CanonicalName | % {
    $computer = $_.Name #name of computer
    $desc = $_.Description #description field associated with computer
    $DistinguishedName = Clean-OU -OriginalOU $_.CanonicalName -Computer $computer #FQDN/RootOU/PROD/WIN7/64bit/LT/PF-123456
    # is PC in the SpecialGroup security group?
    If ($_.memberof -match "SpecialGroup"){[string]$memberOf = "SpecialGroup"}else{$memberOf = "N/A"}
    If ($desc){#if Desc = true
    If (($desc.StartsWith("AEHT")) -or ($desc.StartsWith("VF-")) -or ($desc.StartsWith("Disabeled:"))) {
    $descArr = $desc.Split(":").Trim()
    $descWho = $descArr[0]
    $description = $descArr[1]
    $dwTemp = $descArr[2]
    If ($dwTemp -match "\[IT Support\]"){$dwPrefix = "IT Support"}
    elseif($dwTemp -match "\[App Dev\]"){$dwPrefix = "App Dev"}
    elseIf($dwTemp -match "\[Business\]"){$dwPrefix = "Business"}
    $dwTemp = $dwTemp -replace "\[IT Support\]" -replace "\[App Dev\]" -replace"\[Business\]"
    $descWhen = "$dwPrefix - $dwTemp"
    Write-Host $Computer -NoNewline
    #Write-Host - $memberOf -NoNewline
    #Write-Host - $enabled -NoNewline
    Write-Host - $descWho -NoNewline
    Write-Host - $description -NoNewline
    Write-Host - $descWhen -NoNewline
    Write-Host
    $Record = @{"Computer" = $Computer}
    $record.add("DescByWho",$descWho)
    $record.add("Description",$description)
    $record.add("DescWhen",$descWhen)
    $record.add("OU",$DistinguishedName)
    $record.add("MemberOf",$memberof)
    New-Object PSObject -Property $record |Sort-Object -Property DescByWho | Select Computer, DescByWho, Description, DescWhen, MemberOf, OU
    } | export-csv -path $path -NoTypeInformation

    Hi Mike,
    If you want to divide the output to two csv files based on the variable $descWho, please refer to this script, please also note I havn't tested:
    #modify
    $path1 = "$ScriptDirectory\ad_report_1.csv" #path to where report is saved
    $path2 = "$ScriptDirectory\ad_report_2.csv" #path to where report is saved
    $output1=@()
    $output2=@()
    #modify
    Get-ADComputer -Filter * -Properties Description,Enabled,MemberOf,CanonicalName | % {
    $computer = $_.Name #name of computer
    $desc = $_.Description #description field associated with computer
    $DistinguishedName = Clean-OU -OriginalOU $_.CanonicalName -Computer $computer #FQDN/RootOU/PROD/WIN7/64bit/LT/PF-123456
    # is PC in the SpecialGroup security group?
    If ($_.memberof -match "SpecialGroup"){[string]$memberOf = "SpecialGroup"}else{$memberOf = "N/A"}
    If ($desc){#if Desc = true
    If (($desc.StartsWith("AEHT")) -or ($desc.StartsWith("VF-")) -or ($desc.StartsWith("Disabeled:"))) {
    $descArr = $desc.Split(":").Trim()
    $descWho = $descArr[0]
    $description = $descArr[1]
    $dwTemp = $descArr[2]
    If ($dwTemp -match "\[IT Support\]"){$dwPrefix = "IT Support"}
    elseif($dwTemp -match "\[App Dev\]"){$dwPrefix = "App Dev"}
    elseIf($dwTemp -match "\[Business\]"){$dwPrefix = "Business"}
    $dwTemp = $dwTemp -replace "\[IT Support\]" -replace "\[App Dev\]" -replace"\[Business\]"
    $descWhen = "$dwPrefix - $dwTemp"
    Write-Host $Computer -NoNewline
    #Write-Host - $memberOf -NoNewline
    #Write-Host - $enabled -NoNewline
    Write-Host - $descWho -NoNewline
    Write-Host - $description -NoNewline
    Write-Host - $descWhen -NoNewline
    Write-Host
    $Record = @{"Computer" = $Computer}
    $record.add("DescByWho",$descWho)
    $record.add("Description",$description)
    $record.add("DescWhen",$descWhen)
    $record.add("OU",$DistinguishedName)
    $record.add("MemberOf",$memberof)
    #modify
    New-Object PSObject -Property $record
    if($descWho -like "a*"){ #use if statement to filter the $descwho begin with "a" character
    $output1+=New-Object PSObject -Property $record}
    else{
    $output2+=New-Object PSObject -Property $record}
    $output1|Sort-Object -Property DescByWho | Select Computer, DescByWho, Description, DescWhen, MemberOf, OU|export-csv -path $path1 -NoTypeInformation
    $output2|Sort-Object -Property DescByWho | Select Computer, DescByWho, Description, DescWhen, MemberOf, OU|export-csv -path $path2 -NoTypeInformation
    Best Regards,
    Anna Wang

Maybe you are looking for

  • Using my home Mac as a server

    I would like to put my pictures on the web so that certain clients can view their photos with password. I photograph weddings and would prefer to make html slide shows of their wedding pictures so that they can view them anywhere with any computer. I

  • In the keybourd of my mac 10.8.3 OSX, some battons are not working

    n the keybourd of my mac 10.8.3 OSX, some battons are not working

  • IChat and 10.4.3

    Has anyone heard or seen what the forthcoming OS 10.4.3 update will do for iChat?

  • Excel Data Only export fails (sometimes)

    Using Crystal 12, RPT has a sub-report. All other reports in application work fine.  All other formats (including Excel) work fine with this report. When the user chooses to export the report, if there is "enough" data the report will gpf.  Enough in

  • Root is mounted as read-only

    Hello, I 've installed arch 2009.08 but when i am booting into my system a message appears that my / is mounted as ro (read-only) I ve to run mount -n -o remount,rw / to make it writtable. I ve used ext4 for / and /home partitions and ext3 for /boot