Dynamic procedure to output csv file

Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production
PL/SQL Release 11.1.0.6.0 - Production
CORE     11.1.0.6.0     Production
TNS for Linux: Version 11.1.0.6.0 - Production
NLSRTL Version 11.1.0.6.0 - Production
I am trying to create a procedure to output a csv file, with the table name as input. I can get the field header out no problem, but am struggling with the data! Have looked at ref cursors, and dbms_sql, but am unsure which, if any, can be used for this?
This is what I have so far:
CREATE OR REPLACE PROCEDURE csv_extract_prc (in_table IN VARCHAR2)
AS
   CURSOR c1
   IS
        SELECT   column_name
          FROM   user_tab_columns
         WHERE   UPPER (table_name) = UPPER (in_table)
      ORDER BY   column_id;
   v_output   VARCHAR2 (4000);
   v_file     UTL_FILE.file_type;
BEGIN
   v_file :=
      UTL_FILE.fopen (location       => 'DATAPUMP',
                      filename       => in_table || '.csv',
                      open_mode      => 'w',
                      max_linesize   => 32767);
   FOR r1 IN c1
   LOOP
      v_output := v_output || r1.column_name || ';';
   END LOOP;
   UTL_FILE.put_line (v_file, v_output);
   UTL_FILE.fclose (v_file);
EXCEPTION
   WHEN OTHERS
   THEN
      DBMS_OUTPUT.put_line (SQLERRM);
      UTL_FILE.fclose (v_file);
END csv_extract_prc;
CREATE TABLE test_table (field1 VARCHAR2 (10), field2 NUMBER (10));
exec csv_extract_prc('test_table');Any pointers would be most welcome.

Or this
Re: how to make comma seperated file

Similar Messages

  • Output CSV File Naming Convention - Receiver File Adapter

    Dear SAP experts,
    I need help regarding my scenario.
    My scenario is this, Customer will send EDI message to XI. XI will then translate the message and convert it into XML.. After, a Receiver File Adapter will receive the XML then convert it into .csv file.
    I've already configured the Receiver File Adapter to convert the XML into .csv file.
    But, my problem now is how will I configure to have my output .csv file has a File Naming Convention.
    The output .csv file must be "CustomerName_YearMonthDate".
    From the EDI message, there is indicated Sender GLN in which, each customer has its own Sender GLN.
    E.g., Globus --> 200, Karstadt --> 300,  Metro --> 400.
    How will I configure so that I can have an output .csv file of,
    If Globus sends the EDI message, the output .csv file is Globus_20080304.csv.
    If Karstadt, Karstadt_20080304.csv.
    If Metro, Metro_20080304.csv.
    Kindly advise for a clear and complete solution.
    Thank you very much for your usual support.
    Fred

    Hi Nisar,
    My target message (XML) in the mapping is this,
    - <ns0:CSV>
        -  <SLI>
               <PERIO> </PERIO>
               <ILN> </ILN?
               <EAN> </EAN>
    perio, iln, and ean was rooted on SLI field. and the CSV is the rootnode of the target message.
    I have created a UDF on the message mapping to accomodate the output customer name, here is the codes:
    String fname="";
    if(GLN.equals("23456"))
    fname ="Globus" +dat;
    else if(GLN.equals("5678"))
    fname ="Karstadt"+dat;
    else if(GLN.equals("6789"))
    fname ="Metro"+dat;
    DynamicConfiguration conf = (DynamicConfiguration) container
        .getTransformationParameters()
        .get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
    DynamicConfigurationKey key = DynamicConfigurationKey.create(
        "http://sap.com/xi/XI/System/File",
        "FileName");
        conf.put(key,fname );
    E.g.,
    Globus --> 23456 (Sender GLN)
    Karstadt --> 5678 (Sender GLN)
    Metro --> 6789 (Sender GLN)
    This UDF i've made in the Message Mapping was mapped in the root node CSV.
    Is this UDF correct?
    Then on the File Receiver Configurations, here are the configs,
    Transport Protocol: File System (NFS)
    Message Protocol: File Content Conversion
    Adapter Engine: Integration Server
    File Access Parameters
    Target Directory: /var/opt/gsss/sample/csv
    File Name Scheme: .csv
    Processing Parameters
    File Construction Mode: Create
    - Overwrite Existing File
    Write Mode: Directly
    File Type: Text
    Variable Substitution --> ???
    Adapter Specific Message Attributes
    - Use Adapter-Specific Message Attributes
    - Fail if Adapter-Specific Message Attributes Missing
    - File Name
    Run Operating System Command After Message Processing
    Command Line: chmod 664%F
    Content Conversion Parameters
    Recordset Structure: SLI
    SLI.addHeaderLine: 3
    SLI.headerLine: PERIO;ILN;EAN
    SLI.fieldSeparator: ;
    SLI.endSeparator: 'nl'
    Adapter Status:
    Status: Active
    Kindly advise if my configs are correct.
    Thank you very much!
    Fred

  • Output csv file with blank line

    Hi Fellow PI friend,
    I encountered 1 problem where my output csv file always come with 2 blank lines after data line record. Can someone give me some advise or tip how to solve it?
    Thanks in advance.

    Hi ,
       Check if this link throws some light on your issue:
    Junk character at end of file from sender adapter creating a blank record
    Regards,
    Ravi

  • Output CSV file problem

    Hi Guru,
    I encounted 1 problem where my output csv file content incorrect. Source is from SAP Proxy.
    Example my csv file should have Material code, material description and date. However when i open the csv file, it is only have material code in one line and the rest of fields are not display in the csv file.
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:MT_PRD_MASTER_SND xmlns:ns0="http://com.starhub/sapprdcat">
       <RECORDSET>    1:1
          <RECORD>       1:unbounded
             <MATNR/>
             <MAKTX/>
             <DATE_ADD/>
          </RECORD>
       </RECORDSET>
    </ns0:MT_PRD_MASTER_SND>
    My source and target are same.
    CC Receiver setting:
    Transport Protocal : File System NFS
    Message Protocal : File Content Conversion
    Adapter Engine : Integration Server
    Recordset Structure : RECORD
    RECORD.fiedlNames : MATNR,MAKTX,DATE_ADD
    RECORD.endSeparator :  'nl'
    RECORD.fieldSeparator : ,
    RECORD.processFieldNames: fromConfiguration
    RECORD.addHeaderLine: 0
    The INCORRECT result only display MATNR in one line only.
    HNOK0000102     HNOK0000108     C032S31384A     C032S3XDATA     CFGSC300300     CRAWC300001
    Expected Result should be :
    HNOK0000102,Material test 1,01/01/2007
    HNOK0000108,Material test 2,01/02/2007
    C032S31384A,Material test 3,01/01/2007
    C032S3XDATA,Material test 4,01/01/2007
    CFGSC300300,Material test 5,01/01/2007
    CRAWC300001,Material test 6,01/01/2007
    Thank you very much for help.
    Regards,

    hi,
    check this parameter:
    Recordset Structure : RECORD  [wrong]
    Recordset Structure : RECORDSET,RECORD [right]
    and the other parameters will be like this:
    RECORD.fiedlNames : MATNR,MAKTX,DATE_ADD
    RECORD.endSeparator : 'nl'
    RECORD.fieldSeparator : ,
    RECORD.processFieldNames: fromConfiguration
    RECORD.addHeaderLine: 0
    <b>RECORDSET.fieldSeparator: 'nl'</b>
    Sachin
    Message was edited by:
            Sachin Dhingra

  • Dynamic Distribution Group via csv file and Recipient Filter

    Hello,
    I am trying to create powershell command that will read a CSV file for "Name" and "Dept" and create a Dynamic Distribution Group based on the following Recipient Filter.
    Import-CSV Dist.csv | ForEach-Object {New-DynamicDistributionGroup -Name $_.Name -RecipientFilter {((((((Department -like $_.Dept) -and (RecipientType -eq 'UserMailbox'))) -and (UserAccountControl -ne 'AccountDisabled, NormalAccount'))) -and (-not(Name -like
    'SystemMailbox{*')) -and (-not(Name -like 'CAS_{*')))}
    I keep getting an error that "Missing closing '}" in statement block Char:314.  I added a "}" at the end of the command but then the command fails to read the .csv file.
    Assistance would be greatly appreciated to determine what I am missing.  I have over 100 Dynamic Distribution list to create.
    Cheers

    You're definitely missing a closing curly bracket.
    You have a lot of superfluous parentheses in that expression.  You could certainly simplify it.
    Ed Crowley MVP "There are seldom good technological solutions to behavioral problems."

  • Output .csv file

    In the reports you can specify the file name for the .csv output. But can you specify the path for this file, because it's automatically save it in a temp folder.

    Iya,
    The path for downloaded CSV files (and any other files, for that matter) is a browser-based preference. Please consult your browser's documentation to determine how to specify the path.
    Thanks,
    - Scott -

  • Thread:how to stored procedure stored in csv file in oracle

    can any one help me out please.
    db--oracle(10.2.0.4)
    platform-linux(64)
    we need to export data from a table into a .csv file.
    please help me out.
    thanks

    Hello,
    i have created function but as i run below :
    declare
      2      l_rows    number;
      3  begin
      4      l_rows := dump_csv( 'select *
      5                             from all_users
      6                            where rownum < 5',
      7                          ',',
      8                          '/tmp',
      9                          'test.dat' );
    10      dbms_output.put_line( to_char(l_rows) ||
    11                            ' rows extracted to ascii file' );
    12  end;
    13  /
    declare
    ERROR at line 1:
    ORA-29280: invalid directory path
    ORA-06512: at "SYS.UTL_FILE", line 29
    ORA-06512: at "SYS.UTL_FILE", line 448
    ORA-06512: at "SYS.DUMP_CSV", line 15
    ORA-06512: at line 4Error is occour
    how could i resolve this.
    thanks

  • Extract Members List of "Selected AD Groups" :: Input: CSV File :: OUTPUT: CSV File (URGENT REQUIREMENT)

    Hello Everyone,
    I am looking for a script which extracts AD Group Members (sourced from CSV/TXT file) and Output to CSV/TXT file.
    Can someone help me finding customized script to solve the purpose.
    Quick response is much much appreciated.
    Thanks & Regards,
    Amit Kumar

    Create a CSV with your headers and use this
    Import-Module Activedirectory
    $Groups=Import-Csv -Path "C:\Users\seimi\Documents\ADGroups.csv"
    foreach ($Entry in $Groups) {
    $Path="C:\Users\seimi\Documents\"+ $Entry.groupname +".csv"
    $Users=(Get-ADGroupMember -Identity $entry.groupname | select -ExpandProperty Name) -join ","
    Add-Content -Path "C:\Users\seimi\Documents\PipeGroup.csv" -Value ($Entry.groupname +";" + $Users)
    Seidl Michael | http://www.techguy.at |
    twitter.com/techguyat | facebook.com/techguyat

  • Extract Members of "Selected AD Groups" :: Input: CSV File :: OUTPUT: CSV File

    Dear Leaders,
    I am looking for a script to extracts AD Group Members (sourced from CSV/TXT file) and Output to CSV/TXT file.
    Can someone help me with this customized script.
    In particular I am looking for a script which generates SINGLE OUTPUT file in following format.
    GroupName    GroupMembers
    ADGroup1    Member1,Member2,Member3
    ADGroup2    Member1,Member2,Member3
    ADGroup3    Member1,Member2,Member3
    Thank You Very much in advance !!
    Regards,
    Amit Kumar Rao

    Get-ADGroup -Filter "GroupCategory -eq 'Security'" -SearchBase "OU=Organization-Unit"For Help:Get-Help Get-ADGroup -Examplesif examples not thereUpdate-Help

  • Javascript garbage in output .csv file

    Hi All,
    htmldb version is 1.6.1.00.02
    I have a tabular form with csv output enabled.
    The tail of the file:
    "","08/05/2005","36","28487","3","15.60","30.000","14.00","454.00"
    "","12/05/2005","36","28931","3","15.60","33.040","15.42","500.00"
    "","15/05/2005","36","29100","3","15.60","33.040","15.46","499.96"
    "Èòîãî:","","","","","","2,894.009","942.38","38,415.36"
    <script type="text/javascript">
    var rowStyle = new Array(10);
    var rowActive = new Array(10);
    var rowStyleHover = new Array(10);
    rowStyle[1]='';
    rowStyleHover[1]='';
    rowActive[1]='N';
    rowStyle[2]='';
    rowStyleHover[2]='';
    rowStyle[75]='';
    rowStyleHover[75]='';
    rowActive[75]='N';
    function checkAll(masterCheckbox) {
    if (masterCheckbox.checked) {
    for (var i = 0; i<document.wwv_flow.f01.length; i++) {
    if (document.wwv_flow.f01.checked==false) {
    document.wwv_flow.f01[i].checked=true;

    Sure enough - works fine on a regular tabular report and all pages that are MRU get the javascript garbage.
    My solution for this is going to be putting a link on the bottom of the region on the MRU page that goes to a regular tabular report page that looks exactly like the MRU page and enabling CSV output for that page. Not the most elegant but it should work.
    Earl Lewis

  • 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 --

  • How to create csv file in stored procedure

    I want the output of my stored procedure in a csv file. How can I do that?

    1) define File Paths
    2) Write the output comma seperated to the file.
    Simple :)
    Hope you are comfortable with File operations.
    URL for your reference
    PL/SQL output to .CSV file
    Regards,
    Bhushan

  • Importing CSV file and converting to an Array

    Hi all,
    I'm working on a site that is importing a published CSV (comma seperated values) via actionscript 3.0 URLloader().  Right now I'm just trying to get actionscript to successfully input the imported data from the CSV into an Array, so the CSV file has only 1 cell which contains "athleticMaroon,charcoal,colonialBlue,kellyGreen,fullColor".
    Here's the code I'm using:
    //create new array
    var shirtLiveIntense_btn_Colors:Array=new Array();
    //run CSV data import
    URLLoaderCSV();
    shirtLiveIntense_btn.addEventListener(MouseEvent.CLICK, selectingLogo);
    function selectingLogo(e:MouseEvent):void{
              trace ("logo selected");
              var colorButtons:Array=this[e.currentTarget.name+"_Colors"];
              for (var i:uint=0; i<colorButtons.length; i++) {
                        colorButtons[i].ivar=i;
                        colorButtons[i].addEventListener(MouseEvent.CLICK, shirtColorOption);
    //CSV data import function
    function URLLoaderCSV() {
                var loader:URLLoader = new URLLoader();
                configureListeners(loader);
                var request:URLRequest = new URLRequest("https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AlJnOKOffTSxdFk0RVlEUTVHeF9 DMHZfZ0JzSkJjZFE&single=true&gid=1&output=csv");
                try {
                    loader.load(request);
                } catch (error:Error) {
                    trace("Unable to load requested document.");
    function configureListeners(dispatcher:IEventDispatcher):void {
                dispatcher.addEventListener(Event.COMPLETE, completeHandler);
                dispatcher.addEventListener(Event.OPEN, openHandler);
                dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
                dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
                dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
                dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
    function completeHandler(event:Event):void {
                var loader:URLLoader = URLLoader(event.target);
                trace("completeHandler: " + loader.data);
                                  shirtLiveIntense_btn_Colors.push(loader.data);
    function openHandler(event:Event):void {
                trace("openHandler: " + event);
    function progressHandler(event:ProgressEvent):void {
                trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
    function securityErrorHandler(event:SecurityErrorEvent):void {
                trace("securityErrorHandler: " + event);
    function httpStatusHandler(event:HTTPStatusEvent):void {
                trace("httpStatusHandler: " + event);
    function ioErrorHandler(event:IOErrorEvent):void {
                trace("ioErrorHandler: " + event);
    Here is the output:
    openHandler: [Event type="open" bubbles=false cancelable=false eventPhase=2]
    progressHandler loaded:57 total: 0
    httpStatusHandler: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=200]
    completeHandler: athleticMaroon,charcoal,colonialBlue,kellyGreen,fullColor
    logo selected
    ReferenceError: Error #1056: Cannot create property ivar on String.
              at main_fla::MainTimeline/selectingLogo()
    Examining the output results, I see it is clearly loading the data from the CSV file correctly, but what I think it's doing is importing the data as one string, aka "athleticMaroon,charcoal,colonialBlue,kellyGreen,fullColor", and pushing it to shirtLiveIntense_btn_Colors:Array=new Array().  But, as I see from the error, function selectingLogo(e:MouseEvent) can't process the array because it contains a string.
    If I switch out shirtLiveIntense_btn_Colors.push(loader.data); with shirtLiveIntense_btn_Colors.push(athleticMaroon,charcoal,colonialBlue,kellyGreen,fullColor);, everything works like a charm, but I need the array to be assigned from the dynamic data in the CSV file.
    Can anyone lend a hand in getting the imported stringed CSV data pushed to an accessable array?
    Thanks!

    Thanks kglad for the reply.
    I substituted shirtLiveIntense_btn_Colors.push(loader.data); for shirtLiveIntense_btn_Colors=loader.data.split(","); like you suggested, but I still got the same output:
    openHandler: [Event type="open" bubbles=false cancelable=false eventPhase=2]
    progressHandler loaded:57 total: 0
    httpStatusHandler: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=200]
    completeHandler: athleticMaroon,charcoal,colonialBlue,kellyGreen,fullColor
    athleticMaroon,charcoal,colonialBlue,kellyGreen,fullColor
    logo selected
    ReferenceError: Error #1056: Cannot create property ivar on String.
              at main_fla::MainTimeline/selectingLogo()
    I also tried shirtLiveIntense_btn_Colors.push(loader.data.split(",")); and it gave me the following output instead:
    openHandler: [Event type="open" bubbles=false cancelable=false eventPhase=2]
    progressHandler loaded:57 total: 0
    httpStatusHandler: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=200]
    completeHandler: athleticMaroon,charcoal,colonialBlue,kellyGreen,fullColor
    athleticMaroon,charcoal,colonialBlue,kellyGreen,fullColor
    logo selected
    TypeError: Error #1006: addEventListener is not a function.
              at main_fla::MainTimeline/selectingLogo()
    Any ideas?
    Thanks for the help!

  • How to process large input CSV file with File adapter

    Hi,
    could someone recommend me the right BPEL way to process the large input CSV file (4MB or more with at least 5000 rows) with File Adapter?
    My idea is to receive data from file (poll the UX directory for new input file), transform it and then export to one output CSV file (input for other system).
    I developed my process that consists of:
    - File adapter partnerlink for read data
    - Receive activity with checked box to create instance
    - Transform activity
    - Invoke activity for writing to output CSV.
    I tried this with small input file and everything was OK, but now when I try to use the complete input file, the process doesn't start and automatically goes to OFF state in BPEL console.
    Could I use the MaxTransactionSize parameter as in DB adapter, should I batch the input file or other way could help me?
    Any hint from you? I've to solve this problem till this thursday.
    Thanks,
    Milan K.

    This is a known issue. Martin Kleinman has posted several issues on the forum here, with a similar scenario using ESB. This can only be solved by completely tuning the BPEL application itself, and throwing in big hardware.
    Also switching to the latest 10.1.3.3 version of the SOA Suite (assuming you didn't already) will show some improvements.
    HTH,
    Bas

  • Script that enables mail users and kicks out two csv files

    I am working on a script that will mainly be used as a scheduled task to enabled mailuser by calling the update-recipient command. 
    But before it calls that command it will get for various issues that can cause errors.
    Missing PrimarySMTP
    Display name having a space at front or back.
    The external email address being blank.
    I have IF statements setup to check for those and then call a function that will save into an array the issue for that user. 
    Here is the script
    <#
    .SYNOPSIS
    Enable-MailUsers Synced Mail Users in the Exchange environment
    THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
    RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
    Version .9, 30 June 2014
    .DESCRIPTION
    This script mail-enables Synced Mail Users and creates a CSV report of mail users that were enabled.
    The following is shown:
    * Report Generation Time
    .PARAMETER SendMail
    Send Mail after completion. Set to $True to enable. If enabled, -MailFrom, -MailTo, -MailServer are mandatory
    .PARAMETER MailFrom
    Email address to send from. Passed directly to Send-MailMessage as -From
    .PARAMETER MailTo
    Email address to send to. Passed directly to Send-MailMessage as -To
    .PARAMETER MailServer
    SMTP Mail server to attempt to send through. Passed directly to Send-MailMessage as -SmtpServer
    .PARAMETER ScheduleAs
    Attempt to schedule the command just executed for 10PM nightly. Specify the username here, schtasks (under the hood) will ask for a password later.
    .EXAMPLE
    Generate the HTML report
    .\Enable-MailUsers.ps1 -SendMail -MailFrom [email protected] -MailTo [email protected] -MailServer ex1.contoso.com -ScheduleAs SvcAccount
    #>
    param(
    [parameter(Position=0,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Send Mail ($True/$False)')][bool]$SendMail=$false,
    [parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail From')][string]$MailFrom,
    [parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail To')]$MailTo,
    [parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail Server')][string]$MailServer,
    [parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Schedule as user')][string]$ScheduleAs
    # Sub Function to neatly update progress
    function _UpProg1
    param($PercentComplete,$Status,$Stage)
    $TotalStages=5
    Write-Progress -id 1 -activity "Mail enabled Objects" -status $Status -percentComplete (($PercentComplete/$TotalStages)+(1/$TotalStages*$Stage*100))
    #Sub Function create ErrObject output
    function _ErrObject{
    Param($name,
    $errStatus
    If(!$err){
    Write-Host "error detected"
    $script:err = $True
    $ErrObject = New-Object -TypeName PSObject
    $Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
    $Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
    $script:ErrOutput += $ErrObject
    # 1. Initial Startup
    # 1.0 Check Powershell Version
    if ((Get-Host).Version.Major -eq 1)
    throw "Powershell Version 1 not supported";
    # 1.1 Check Exchange Management Shell, attempt to load
    if (!(Get-Command Get-ExchangeServer -ErrorAction SilentlyContinue))
    if (Test-Path "D:\Exchsrvr\bin\RemoteExchange.ps1")
    . 'D:\Exchsrvr\bin\RemoteExchange.ps1'
    Connect-ExchangeServer -auto
    } elseif (Test-Path "D:\Exchsrvr\bin\Exchange.ps1") {
    Add-PSSnapIn Microsoft.Exchange.Management.PowerShell.Admin
    .'D:\Exchsrvr\bin\Exchange.ps1'
    } else {
    throw "Exchange Management Shell cannot be loaded"
    # 1.2 Check if -SendMail parameter set and if so check -MailFrom, -MailTo and -MailServer are set
    if ($SendMail)
    if (!$MailFrom -or !$MailTo -or !$MailServer)
    throw "If -SendMail specified, you must also specify -MailFrom, -MailTo and -MailServer"
    # 1.3 Check Exchange Management Shell Version
    if ((Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue))
    $E2010 = $false;
    if (Get-ExchangeServer | Where {$_.AdminDisplayVersion.Major -gt 14})
    Write-Warning "Exchange 2010 or higher detected. You'll get better results if you run this script from an Exchange 2010/2013 management shell"
    }else{
    $E2010 = $true
    $localserver = get-exchangeserver $Env:computername
    $localversion = $localserver.admindisplayversion.major
    if ($localversion -eq 15) { $E2013 = $true }
    #Get date
    $filedate = get-date -uformat "%m-%d-%Y"
    $filedate = $filedate.ToString().Replace("0", "")
    #Get the valid users that are not mail-enabled
    _UpProg1 1 "Getting User List" 1
    #$Users = Get-mailuser -ResultSize unlimited -OrganizationalUnit "R0018.COLLABORATION.ECS.HP.COM/Accounts/AbbVienet/Users" | ?{$_.legacyexchangeDN -eq ""}
    $i = 0
    $output = @()
    $errOutput = @()
    $err = $False
    #2 Process users
    ForEach ($User in $Users){
    $i++
    _UpProg1 ($i/$Users.Count*100) "Updating Recipients" 2
    If ($user.ExternalEmailAddress -eq $null){
    _ErrObject $user.Name, "Missing External Email Address"
    ElseIf($user.DisplayName -NotLike "* "){
    _ErrObject $user.Name, "DisplayName contains a trailing space"
    ElseIf($user.DisplayName -NotLike "_*"){
    _ErrObject $user.Name, "DisplayName contains a Leading space"
    ElseIf($user.PrimarySmtpAddress -eq $null){
    _ErrObject $user.Name, "Missing Primary SMTP address"
    Else{
    #Disable EmailAddressPolicy on these users
    Set-Mailuser $User.Name -EmailAddressPolicyEnabled $false
    #pass to Update-recipient
    Update-Recipient $User.Name
    $LEDN = Get-MailUser $User.Name | Select {$_.LegacyExchangeDN}
    If ($LEDN -ne ""){
    $object = New-Object -TypeName PSObject
    $X500 = "x500:" + $LEDN.'$_.LegacyExchangeDN'
    $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $User.Name
    $object | Add-Member -Name 'x500' -MemberType Noteproperty -Value $X500
    $output += $object
    #Creating CSVFile Output
    _UpProg1 99 "Outputting CSV file 3" 3
    $CSVFile = "c:\scripts\Mail-enable\Mailenabled_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
    If($err){
    $ErrCSVFile = "c:\scripts\Mail-enable\ProblemUsers_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
    $errOutput | Select-Object Name, Comment | ConvertTo-CSV -NoTypeInformation > $ErrCSVFIle
    $Output | ConvertTo-Csv -NoTypeInformation > $CSVFile
    if ($SendMail)
    _UpProg1 95 "Sending mail message.." 4
    If($err){
    Send-MailMessage -Attachments $CSVFile,$ErrCSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
    Else{
    Send-MailMessage -Attachments $CSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
    if ($ScheduleAs)
    _UpProg1 99 "Attempting to Schedule Task.." 4
    $dir=(split-path -parent $myinvocation.mycommand.definition)
    $params=""
    if ($SendMail)
    $params+=' -SendMail:$true'
    $params+=" -MailFrom:$MailFrom -MailTo:$MailTo -MailServer:$MailServer"
    $task = "powershell -c \""pushd $dir; $($myinvocation.mycommand.definition) $params\"""
    Write-Output "Attempting to schedule task as $($ScheduleAs)..."
    Write-Output "Task to schedule: $($task)"
    schtasks /Create /RU $ScheduleAs /RP /SC DAILY /ST 22:00 /TN "Enable Mail Users" /TR $task
    The Problem is that when I look at the $errOutput I see things but when I pipe the $erroutput to convertTo-CSV I get this within the CSV file. I think its because I an calling a function to do the updating. But not sure.
    Jeff C

    Hi Jeff,
    Any updates? If you have any other questions, please feel free to let me know.
    A little clarification to the script:
    function _ErrObject{
    Param($name,
    $errStatus
    If(!$err){
    Write-Host "error detected"
    $script:err = $True
    $ErrObject = New-Object -TypeName PSObject
    $Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
    $Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
    $script:ErrOutput += $ErrObject
    $errOutput = @()
    _ErrObject Name, "Missing External Email Address"
    $errOutput
    _ErrObject Name "Missing External Email Address"
    $errOutput
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support

Maybe you are looking for

  • Follow-up srw.message

    hi... just want to follow-up Gladys([email protected]) inquiry because we really need to make it work ASAP!!! Thanks null

  • External tables in oracle 8i

    Hi, I am working in Oracle 8i. I need to use Oracle 8i External Table to load data in the database. But I am getting the following error ORA-00922: Missing or Invalid Option The snippet which I used is as follows: create table ext_table_csv ( a NUMBE

  • 100% view for print docs but not for web based layouts?

    Why do documents view at the correct on screen size when set at 100% for print documents but to view a document at the right pixel size for web it's more like 66.4%? Thanks

  • SAFARI QUITS WHEN PRINTING

    Recently had a MacBook Tune Up performed at at local retail Apple store under the ProCare service plan and all minor issues were resolve except for one which was not noticed until after retuning home from the store. Whenever we try to print from Safa

  • Don't want track # in filename

    I don't want the track # in the filename....is there any way to change this in the import settings for any future CDs that I want to load into my library? Or even better to have it globally change the filename to just the songname??