powershell cmdlet how to pipe information or error to write-eventlog










2















i'm trying to output to eventlog to the correct Entry Type (Information,Warning,Error) based on the stream that is coming out of my cmdlet, something like this:



function myfunction 
Param(
[switch]$stream1,
[switch]$stream2
)
if ($stream1) write-output 'stream 1 msg'
if ($stream2) write-error 'stream 2 msg'


$eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

myfunction -stream1 -stream2 `
1> write-eventlog @eventlogparams -entrytype information -message $_ `
2> write-eventlog @eventlogparams -entrytype error -message $_


does anyone have an idea of how to accomplish this?










share|improve this question
























  • you need a source named myapp on the target system. that is created with the New-Eventlog cmdlet and its -Source parameter. take a look at this article ... How to Use PowerShell to Write to Event Logs – Hey, Scripting Guy! Blog — blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/…

    – Lee_Dailey
    Nov 10 '18 at 18:30






  • 1





    @Lee_Dailey: I think the Write-EventLog arguments are just examples. If I understand correctly, the OP's desire is to process output from all streams (or at least from both the success and error streams) with the ability to distinguish what stream the input came from, so that the behavior can be adjusted accordingly (picking the appropriate event category, in this case).

    – mklement0
    Nov 10 '18 at 21:08







  • 1





    @mklement0 - that makes sense. [grin] i am still uncertain the OP knows that the Source must exist 1st. that is the most common error i have seen folks mention when 1st trying to write to a custom event log.

    – Lee_Dailey
    Nov 10 '18 at 21:15











  • i'm already aware of needing to create the source beforehand

    – ErikW
    Nov 11 '18 at 3:58











  • @ErikW - thank you for clarifying that! [grin]

    – Lee_Dailey
    Nov 11 '18 at 14:08















2















i'm trying to output to eventlog to the correct Entry Type (Information,Warning,Error) based on the stream that is coming out of my cmdlet, something like this:



function myfunction 
Param(
[switch]$stream1,
[switch]$stream2
)
if ($stream1) write-output 'stream 1 msg'
if ($stream2) write-error 'stream 2 msg'


$eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

myfunction -stream1 -stream2 `
1> write-eventlog @eventlogparams -entrytype information -message $_ `
2> write-eventlog @eventlogparams -entrytype error -message $_


does anyone have an idea of how to accomplish this?










share|improve this question
























  • you need a source named myapp on the target system. that is created with the New-Eventlog cmdlet and its -Source parameter. take a look at this article ... How to Use PowerShell to Write to Event Logs – Hey, Scripting Guy! Blog — blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/…

    – Lee_Dailey
    Nov 10 '18 at 18:30






  • 1





    @Lee_Dailey: I think the Write-EventLog arguments are just examples. If I understand correctly, the OP's desire is to process output from all streams (or at least from both the success and error streams) with the ability to distinguish what stream the input came from, so that the behavior can be adjusted accordingly (picking the appropriate event category, in this case).

    – mklement0
    Nov 10 '18 at 21:08







  • 1





    @mklement0 - that makes sense. [grin] i am still uncertain the OP knows that the Source must exist 1st. that is the most common error i have seen folks mention when 1st trying to write to a custom event log.

    – Lee_Dailey
    Nov 10 '18 at 21:15











  • i'm already aware of needing to create the source beforehand

    – ErikW
    Nov 11 '18 at 3:58











  • @ErikW - thank you for clarifying that! [grin]

    – Lee_Dailey
    Nov 11 '18 at 14:08













2












2








2


1






i'm trying to output to eventlog to the correct Entry Type (Information,Warning,Error) based on the stream that is coming out of my cmdlet, something like this:



function myfunction 
Param(
[switch]$stream1,
[switch]$stream2
)
if ($stream1) write-output 'stream 1 msg'
if ($stream2) write-error 'stream 2 msg'


$eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

myfunction -stream1 -stream2 `
1> write-eventlog @eventlogparams -entrytype information -message $_ `
2> write-eventlog @eventlogparams -entrytype error -message $_


does anyone have an idea of how to accomplish this?










share|improve this question
















i'm trying to output to eventlog to the correct Entry Type (Information,Warning,Error) based on the stream that is coming out of my cmdlet, something like this:



function myfunction 
Param(
[switch]$stream1,
[switch]$stream2
)
if ($stream1) write-output 'stream 1 msg'
if ($stream2) write-error 'stream 2 msg'


$eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

myfunction -stream1 -stream2 `
1> write-eventlog @eventlogparams -entrytype information -message $_ `
2> write-eventlog @eventlogparams -entrytype error -message $_


does anyone have an idea of how to accomplish this?







powershell event-log io-redirection






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 '18 at 20:20









mklement0

127k20241269




127k20241269










asked Nov 10 '18 at 17:54









ErikWErikW

947




947












  • you need a source named myapp on the target system. that is created with the New-Eventlog cmdlet and its -Source parameter. take a look at this article ... How to Use PowerShell to Write to Event Logs – Hey, Scripting Guy! Blog — blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/…

    – Lee_Dailey
    Nov 10 '18 at 18:30






  • 1





    @Lee_Dailey: I think the Write-EventLog arguments are just examples. If I understand correctly, the OP's desire is to process output from all streams (or at least from both the success and error streams) with the ability to distinguish what stream the input came from, so that the behavior can be adjusted accordingly (picking the appropriate event category, in this case).

    – mklement0
    Nov 10 '18 at 21:08







  • 1





    @mklement0 - that makes sense. [grin] i am still uncertain the OP knows that the Source must exist 1st. that is the most common error i have seen folks mention when 1st trying to write to a custom event log.

    – Lee_Dailey
    Nov 10 '18 at 21:15











  • i'm already aware of needing to create the source beforehand

    – ErikW
    Nov 11 '18 at 3:58











  • @ErikW - thank you for clarifying that! [grin]

    – Lee_Dailey
    Nov 11 '18 at 14:08

















  • you need a source named myapp on the target system. that is created with the New-Eventlog cmdlet and its -Source parameter. take a look at this article ... How to Use PowerShell to Write to Event Logs – Hey, Scripting Guy! Blog — blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/…

    – Lee_Dailey
    Nov 10 '18 at 18:30






  • 1





    @Lee_Dailey: I think the Write-EventLog arguments are just examples. If I understand correctly, the OP's desire is to process output from all streams (or at least from both the success and error streams) with the ability to distinguish what stream the input came from, so that the behavior can be adjusted accordingly (picking the appropriate event category, in this case).

    – mklement0
    Nov 10 '18 at 21:08







  • 1





    @mklement0 - that makes sense. [grin] i am still uncertain the OP knows that the Source must exist 1st. that is the most common error i have seen folks mention when 1st trying to write to a custom event log.

    – Lee_Dailey
    Nov 10 '18 at 21:15











  • i'm already aware of needing to create the source beforehand

    – ErikW
    Nov 11 '18 at 3:58











  • @ErikW - thank you for clarifying that! [grin]

    – Lee_Dailey
    Nov 11 '18 at 14:08
















you need a source named myapp on the target system. that is created with the New-Eventlog cmdlet and its -Source parameter. take a look at this article ... How to Use PowerShell to Write to Event Logs – Hey, Scripting Guy! Blog — blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/…

– Lee_Dailey
Nov 10 '18 at 18:30





you need a source named myapp on the target system. that is created with the New-Eventlog cmdlet and its -Source parameter. take a look at this article ... How to Use PowerShell to Write to Event Logs – Hey, Scripting Guy! Blog — blogs.technet.microsoft.com/heyscriptingguy/2013/06/20/…

– Lee_Dailey
Nov 10 '18 at 18:30




1




1





@Lee_Dailey: I think the Write-EventLog arguments are just examples. If I understand correctly, the OP's desire is to process output from all streams (or at least from both the success and error streams) with the ability to distinguish what stream the input came from, so that the behavior can be adjusted accordingly (picking the appropriate event category, in this case).

– mklement0
Nov 10 '18 at 21:08






@Lee_Dailey: I think the Write-EventLog arguments are just examples. If I understand correctly, the OP's desire is to process output from all streams (or at least from both the success and error streams) with the ability to distinguish what stream the input came from, so that the behavior can be adjusted accordingly (picking the appropriate event category, in this case).

– mklement0
Nov 10 '18 at 21:08





1




1





@mklement0 - that makes sense. [grin] i am still uncertain the OP knows that the Source must exist 1st. that is the most common error i have seen folks mention when 1st trying to write to a custom event log.

– Lee_Dailey
Nov 10 '18 at 21:15





@mklement0 - that makes sense. [grin] i am still uncertain the OP knows that the Source must exist 1st. that is the most common error i have seen folks mention when 1st trying to write to a custom event log.

– Lee_Dailey
Nov 10 '18 at 21:15













i'm already aware of needing to create the source beforehand

– ErikW
Nov 11 '18 at 3:58





i'm already aware of needing to create the source beforehand

– ErikW
Nov 11 '18 at 3:58













@ErikW - thank you for clarifying that! [grin]

– Lee_Dailey
Nov 11 '18 at 14:08





@ErikW - thank you for clarifying that! [grin]

– Lee_Dailey
Nov 11 '18 at 14:08












2 Answers
2






active

oldest

votes


















3














You can merge the error stream and others into the success stream and distinguish between the origin streams by the data type of each pipeline object:



myfunction -channel1 -channel2 *>&1 | ForEach-Object 
$entryType = switch ($_.GetType().FullName)
'System.Management.Automation.ErrorRecord' 'error'; break
'System.Management.Automation.WarningRecord' 'warning'; break
default 'information'

write-eventlog @eventlogparams -entrytype $entryType -message $_



Redirection *>&1 sends the output from all (*) streams to (&) the success stream (1), so that all output, irrespective of what stream it came from, is sent through the pipeline.



The above only deals with errors and warnings specifically, and reports everything else, including the success output, as information, but it's easy to extend the approach - see bottom.



See about_Redirections for an overview of all 6 output streams available in PowerShell (as of v6).




To illustrate the technique with a simpler example:



& Write-Output good; Write-Error bad; Write-Warning problematic *>&1 | ForEach-Object 
$entryType = switch ($_.GetType().FullName)
'System.Management.Automation.ErrorRecord' 'error'; break
'System.Management.Automation.WarningRecord' 'warning'; break
default 'information'

'[0] 1' -f $entryType, $_



The above yields:



[information] good
[error] bad
[warning] problematic



The list of data types output by the various streams:



Stream Type
------ ----
#1 (Success) (whatever input type is provided).
#2 (Error) [System.Management.Automation.ErrorRecord]
#3 (Warning) [System.Management.Automation.WarningRecord]
#4 (Verbose) [System.Management.Automation.VerboseRecord]
#5 (Debug) [System.Management.Automation.DebugRecord]
#6 (Information) [System.Management.Automation.InformationRecord]


The following code was used to produce the above list (except for the first data row):



& 
$VerbosePreference = $DebugPreference = $InformationPreference = 'Continue'
$ndx = 2
"Write-Error", "Write-Warning", "Write-Verbose", "Write-Debug", "Write-Information"





share|improve this answer
































    1














    As @Lee_Dailey rightly pointed , you need the event source to exist.Even after that,Your snippet might throw error like (checked in PS v5)




    The process cannot access the file
    'C:UsersusernameDesktopwrite-eventlog' because it is being used by
    another process.




    because redirection operator expects a file to redirect not a cmdlet or function that's the reason for the above error.



    you can try modifying the code so that redirection operator stores the data in files and then push that into event log:



    myfunction -channel1 -channel2 > output.txt 2> error.txt 

    write-eventlog @eventlogparams -entrytype error -message ((get-content error.txt) -join "")

    write-eventlog @eventlogparams -entrytype information -message ((get-content output.txt) -join "")


    Another method is using outvariable and errorvariable , for this to work the function must be advanced function (I have added cmdletbinding for that):



    function myfunction 
    [CmdletBinding()]
    Param(
    [switch]$channel1,
    [switch]$channel2
    )
    if ($channel1) write-output 'channel 1 msg'
    if ($channel2) write-error 'channel 2 msg'


    $eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

    myfunction -channel1 -channel2 -OutVariable output -ErrorVariable errordata
    write-eventlog @eventlogparams -entrytype error -message ($errordata -join "")

    write-eventlog @eventlogparams -entrytype information -message ($output -join "")





    share|improve this answer

























    • Quibble: The reason for the error is that the same file is being targeted twice; PowerShell is perfectly happy to write to a file named write-eventlog, but not via redirections competing for the same output file. Also, I'm not sure that the intent is to write the collected stream output as a single event-log record.

      – mklement0
      Nov 11 '18 at 4:07







    • 1





      the problem with this is that it collects all to a variable, and you can do a foreach statement to split out to eventlog later, but I'm trying to write to eventlog in realtime as things are done inside my function

      – ErikW
      Nov 11 '18 at 4:12






    • 1





      @mklement0 yes .I understood that from the error message,I should have articulated that better in the answer

      – Abhijith pk
      Nov 11 '18 at 4:29










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241825%2fpowershell-cmdlet-how-to-pipe-information-or-error-to-write-eventlog%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    You can merge the error stream and others into the success stream and distinguish between the origin streams by the data type of each pipeline object:



    myfunction -channel1 -channel2 *>&1 | ForEach-Object 
    $entryType = switch ($_.GetType().FullName)
    'System.Management.Automation.ErrorRecord' 'error'; break
    'System.Management.Automation.WarningRecord' 'warning'; break
    default 'information'

    write-eventlog @eventlogparams -entrytype $entryType -message $_



    Redirection *>&1 sends the output from all (*) streams to (&) the success stream (1), so that all output, irrespective of what stream it came from, is sent through the pipeline.



    The above only deals with errors and warnings specifically, and reports everything else, including the success output, as information, but it's easy to extend the approach - see bottom.



    See about_Redirections for an overview of all 6 output streams available in PowerShell (as of v6).




    To illustrate the technique with a simpler example:



    & Write-Output good; Write-Error bad; Write-Warning problematic *>&1 | ForEach-Object 
    $entryType = switch ($_.GetType().FullName)
    'System.Management.Automation.ErrorRecord' 'error'; break
    'System.Management.Automation.WarningRecord' 'warning'; break
    default 'information'

    '[0] 1' -f $entryType, $_



    The above yields:



    [information] good
    [error] bad
    [warning] problematic



    The list of data types output by the various streams:



    Stream Type
    ------ ----
    #1 (Success) (whatever input type is provided).
    #2 (Error) [System.Management.Automation.ErrorRecord]
    #3 (Warning) [System.Management.Automation.WarningRecord]
    #4 (Verbose) [System.Management.Automation.VerboseRecord]
    #5 (Debug) [System.Management.Automation.DebugRecord]
    #6 (Information) [System.Management.Automation.InformationRecord]


    The following code was used to produce the above list (except for the first data row):



    & 
    $VerbosePreference = $DebugPreference = $InformationPreference = 'Continue'
    $ndx = 2
    "Write-Error", "Write-Warning", "Write-Verbose", "Write-Debug", "Write-Information"





    share|improve this answer





























      3














      You can merge the error stream and others into the success stream and distinguish between the origin streams by the data type of each pipeline object:



      myfunction -channel1 -channel2 *>&1 | ForEach-Object 
      $entryType = switch ($_.GetType().FullName)
      'System.Management.Automation.ErrorRecord' 'error'; break
      'System.Management.Automation.WarningRecord' 'warning'; break
      default 'information'

      write-eventlog @eventlogparams -entrytype $entryType -message $_



      Redirection *>&1 sends the output from all (*) streams to (&) the success stream (1), so that all output, irrespective of what stream it came from, is sent through the pipeline.



      The above only deals with errors and warnings specifically, and reports everything else, including the success output, as information, but it's easy to extend the approach - see bottom.



      See about_Redirections for an overview of all 6 output streams available in PowerShell (as of v6).




      To illustrate the technique with a simpler example:



      & Write-Output good; Write-Error bad; Write-Warning problematic *>&1 | ForEach-Object 
      $entryType = switch ($_.GetType().FullName)
      'System.Management.Automation.ErrorRecord' 'error'; break
      'System.Management.Automation.WarningRecord' 'warning'; break
      default 'information'

      '[0] 1' -f $entryType, $_



      The above yields:



      [information] good
      [error] bad
      [warning] problematic



      The list of data types output by the various streams:



      Stream Type
      ------ ----
      #1 (Success) (whatever input type is provided).
      #2 (Error) [System.Management.Automation.ErrorRecord]
      #3 (Warning) [System.Management.Automation.WarningRecord]
      #4 (Verbose) [System.Management.Automation.VerboseRecord]
      #5 (Debug) [System.Management.Automation.DebugRecord]
      #6 (Information) [System.Management.Automation.InformationRecord]


      The following code was used to produce the above list (except for the first data row):



      & 
      $VerbosePreference = $DebugPreference = $InformationPreference = 'Continue'
      $ndx = 2
      "Write-Error", "Write-Warning", "Write-Verbose", "Write-Debug", "Write-Information"





      share|improve this answer



























        3












        3








        3







        You can merge the error stream and others into the success stream and distinguish between the origin streams by the data type of each pipeline object:



        myfunction -channel1 -channel2 *>&1 | ForEach-Object 
        $entryType = switch ($_.GetType().FullName)
        'System.Management.Automation.ErrorRecord' 'error'; break
        'System.Management.Automation.WarningRecord' 'warning'; break
        default 'information'

        write-eventlog @eventlogparams -entrytype $entryType -message $_



        Redirection *>&1 sends the output from all (*) streams to (&) the success stream (1), so that all output, irrespective of what stream it came from, is sent through the pipeline.



        The above only deals with errors and warnings specifically, and reports everything else, including the success output, as information, but it's easy to extend the approach - see bottom.



        See about_Redirections for an overview of all 6 output streams available in PowerShell (as of v6).




        To illustrate the technique with a simpler example:



        & Write-Output good; Write-Error bad; Write-Warning problematic *>&1 | ForEach-Object 
        $entryType = switch ($_.GetType().FullName)
        'System.Management.Automation.ErrorRecord' 'error'; break
        'System.Management.Automation.WarningRecord' 'warning'; break
        default 'information'

        '[0] 1' -f $entryType, $_



        The above yields:



        [information] good
        [error] bad
        [warning] problematic



        The list of data types output by the various streams:



        Stream Type
        ------ ----
        #1 (Success) (whatever input type is provided).
        #2 (Error) [System.Management.Automation.ErrorRecord]
        #3 (Warning) [System.Management.Automation.WarningRecord]
        #4 (Verbose) [System.Management.Automation.VerboseRecord]
        #5 (Debug) [System.Management.Automation.DebugRecord]
        #6 (Information) [System.Management.Automation.InformationRecord]


        The following code was used to produce the above list (except for the first data row):



        & 
        $VerbosePreference = $DebugPreference = $InformationPreference = 'Continue'
        $ndx = 2
        "Write-Error", "Write-Warning", "Write-Verbose", "Write-Debug", "Write-Information"





        share|improve this answer















        You can merge the error stream and others into the success stream and distinguish between the origin streams by the data type of each pipeline object:



        myfunction -channel1 -channel2 *>&1 | ForEach-Object 
        $entryType = switch ($_.GetType().FullName)
        'System.Management.Automation.ErrorRecord' 'error'; break
        'System.Management.Automation.WarningRecord' 'warning'; break
        default 'information'

        write-eventlog @eventlogparams -entrytype $entryType -message $_



        Redirection *>&1 sends the output from all (*) streams to (&) the success stream (1), so that all output, irrespective of what stream it came from, is sent through the pipeline.



        The above only deals with errors and warnings specifically, and reports everything else, including the success output, as information, but it's easy to extend the approach - see bottom.



        See about_Redirections for an overview of all 6 output streams available in PowerShell (as of v6).




        To illustrate the technique with a simpler example:



        & Write-Output good; Write-Error bad; Write-Warning problematic *>&1 | ForEach-Object 
        $entryType = switch ($_.GetType().FullName)
        'System.Management.Automation.ErrorRecord' 'error'; break
        'System.Management.Automation.WarningRecord' 'warning'; break
        default 'information'

        '[0] 1' -f $entryType, $_



        The above yields:



        [information] good
        [error] bad
        [warning] problematic



        The list of data types output by the various streams:



        Stream Type
        ------ ----
        #1 (Success) (whatever input type is provided).
        #2 (Error) [System.Management.Automation.ErrorRecord]
        #3 (Warning) [System.Management.Automation.WarningRecord]
        #4 (Verbose) [System.Management.Automation.VerboseRecord]
        #5 (Debug) [System.Management.Automation.DebugRecord]
        #6 (Information) [System.Management.Automation.InformationRecord]


        The following code was used to produce the above list (except for the first data row):



        & 
        $VerbosePreference = $DebugPreference = $InformationPreference = 'Continue'
        $ndx = 2
        "Write-Error", "Write-Warning", "Write-Verbose", "Write-Debug", "Write-Information"






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 10 '18 at 21:27

























        answered Nov 10 '18 at 20:00









        mklement0mklement0

        127k20241269




        127k20241269























            1














            As @Lee_Dailey rightly pointed , you need the event source to exist.Even after that,Your snippet might throw error like (checked in PS v5)




            The process cannot access the file
            'C:UsersusernameDesktopwrite-eventlog' because it is being used by
            another process.




            because redirection operator expects a file to redirect not a cmdlet or function that's the reason for the above error.



            you can try modifying the code so that redirection operator stores the data in files and then push that into event log:



            myfunction -channel1 -channel2 > output.txt 2> error.txt 

            write-eventlog @eventlogparams -entrytype error -message ((get-content error.txt) -join "")

            write-eventlog @eventlogparams -entrytype information -message ((get-content output.txt) -join "")


            Another method is using outvariable and errorvariable , for this to work the function must be advanced function (I have added cmdletbinding for that):



            function myfunction 
            [CmdletBinding()]
            Param(
            [switch]$channel1,
            [switch]$channel2
            )
            if ($channel1) write-output 'channel 1 msg'
            if ($channel2) write-error 'channel 2 msg'


            $eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

            myfunction -channel1 -channel2 -OutVariable output -ErrorVariable errordata
            write-eventlog @eventlogparams -entrytype error -message ($errordata -join "")

            write-eventlog @eventlogparams -entrytype information -message ($output -join "")





            share|improve this answer

























            • Quibble: The reason for the error is that the same file is being targeted twice; PowerShell is perfectly happy to write to a file named write-eventlog, but not via redirections competing for the same output file. Also, I'm not sure that the intent is to write the collected stream output as a single event-log record.

              – mklement0
              Nov 11 '18 at 4:07







            • 1





              the problem with this is that it collects all to a variable, and you can do a foreach statement to split out to eventlog later, but I'm trying to write to eventlog in realtime as things are done inside my function

              – ErikW
              Nov 11 '18 at 4:12






            • 1





              @mklement0 yes .I understood that from the error message,I should have articulated that better in the answer

              – Abhijith pk
              Nov 11 '18 at 4:29















            1














            As @Lee_Dailey rightly pointed , you need the event source to exist.Even after that,Your snippet might throw error like (checked in PS v5)




            The process cannot access the file
            'C:UsersusernameDesktopwrite-eventlog' because it is being used by
            another process.




            because redirection operator expects a file to redirect not a cmdlet or function that's the reason for the above error.



            you can try modifying the code so that redirection operator stores the data in files and then push that into event log:



            myfunction -channel1 -channel2 > output.txt 2> error.txt 

            write-eventlog @eventlogparams -entrytype error -message ((get-content error.txt) -join "")

            write-eventlog @eventlogparams -entrytype information -message ((get-content output.txt) -join "")


            Another method is using outvariable and errorvariable , for this to work the function must be advanced function (I have added cmdletbinding for that):



            function myfunction 
            [CmdletBinding()]
            Param(
            [switch]$channel1,
            [switch]$channel2
            )
            if ($channel1) write-output 'channel 1 msg'
            if ($channel2) write-error 'channel 2 msg'


            $eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

            myfunction -channel1 -channel2 -OutVariable output -ErrorVariable errordata
            write-eventlog @eventlogparams -entrytype error -message ($errordata -join "")

            write-eventlog @eventlogparams -entrytype information -message ($output -join "")





            share|improve this answer

























            • Quibble: The reason for the error is that the same file is being targeted twice; PowerShell is perfectly happy to write to a file named write-eventlog, but not via redirections competing for the same output file. Also, I'm not sure that the intent is to write the collected stream output as a single event-log record.

              – mklement0
              Nov 11 '18 at 4:07







            • 1





              the problem with this is that it collects all to a variable, and you can do a foreach statement to split out to eventlog later, but I'm trying to write to eventlog in realtime as things are done inside my function

              – ErikW
              Nov 11 '18 at 4:12






            • 1





              @mklement0 yes .I understood that from the error message,I should have articulated that better in the answer

              – Abhijith pk
              Nov 11 '18 at 4:29













            1












            1








            1







            As @Lee_Dailey rightly pointed , you need the event source to exist.Even after that,Your snippet might throw error like (checked in PS v5)




            The process cannot access the file
            'C:UsersusernameDesktopwrite-eventlog' because it is being used by
            another process.




            because redirection operator expects a file to redirect not a cmdlet or function that's the reason for the above error.



            you can try modifying the code so that redirection operator stores the data in files and then push that into event log:



            myfunction -channel1 -channel2 > output.txt 2> error.txt 

            write-eventlog @eventlogparams -entrytype error -message ((get-content error.txt) -join "")

            write-eventlog @eventlogparams -entrytype information -message ((get-content output.txt) -join "")


            Another method is using outvariable and errorvariable , for this to work the function must be advanced function (I have added cmdletbinding for that):



            function myfunction 
            [CmdletBinding()]
            Param(
            [switch]$channel1,
            [switch]$channel2
            )
            if ($channel1) write-output 'channel 1 msg'
            if ($channel2) write-error 'channel 2 msg'


            $eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

            myfunction -channel1 -channel2 -OutVariable output -ErrorVariable errordata
            write-eventlog @eventlogparams -entrytype error -message ($errordata -join "")

            write-eventlog @eventlogparams -entrytype information -message ($output -join "")





            share|improve this answer















            As @Lee_Dailey rightly pointed , you need the event source to exist.Even after that,Your snippet might throw error like (checked in PS v5)




            The process cannot access the file
            'C:UsersusernameDesktopwrite-eventlog' because it is being used by
            another process.




            because redirection operator expects a file to redirect not a cmdlet or function that's the reason for the above error.



            you can try modifying the code so that redirection operator stores the data in files and then push that into event log:



            myfunction -channel1 -channel2 > output.txt 2> error.txt 

            write-eventlog @eventlogparams -entrytype error -message ((get-content error.txt) -join "")

            write-eventlog @eventlogparams -entrytype information -message ((get-content output.txt) -join "")


            Another method is using outvariable and errorvariable , for this to work the function must be advanced function (I have added cmdletbinding for that):



            function myfunction 
            [CmdletBinding()]
            Param(
            [switch]$channel1,
            [switch]$channel2
            )
            if ($channel1) write-output 'channel 1 msg'
            if ($channel2) write-error 'channel 2 msg'


            $eventlogparams = @'logname'='application';'source'='myapp';'eventid'='1'

            myfunction -channel1 -channel2 -OutVariable output -ErrorVariable errordata
            write-eventlog @eventlogparams -entrytype error -message ($errordata -join "")

            write-eventlog @eventlogparams -entrytype information -message ($output -join "")






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 10 '18 at 19:43

























            answered Nov 10 '18 at 18:41









            Abhijith pkAbhijith pk

            2,7431914




            2,7431914












            • Quibble: The reason for the error is that the same file is being targeted twice; PowerShell is perfectly happy to write to a file named write-eventlog, but not via redirections competing for the same output file. Also, I'm not sure that the intent is to write the collected stream output as a single event-log record.

              – mklement0
              Nov 11 '18 at 4:07







            • 1





              the problem with this is that it collects all to a variable, and you can do a foreach statement to split out to eventlog later, but I'm trying to write to eventlog in realtime as things are done inside my function

              – ErikW
              Nov 11 '18 at 4:12






            • 1





              @mklement0 yes .I understood that from the error message,I should have articulated that better in the answer

              – Abhijith pk
              Nov 11 '18 at 4:29

















            • Quibble: The reason for the error is that the same file is being targeted twice; PowerShell is perfectly happy to write to a file named write-eventlog, but not via redirections competing for the same output file. Also, I'm not sure that the intent is to write the collected stream output as a single event-log record.

              – mklement0
              Nov 11 '18 at 4:07







            • 1





              the problem with this is that it collects all to a variable, and you can do a foreach statement to split out to eventlog later, but I'm trying to write to eventlog in realtime as things are done inside my function

              – ErikW
              Nov 11 '18 at 4:12






            • 1





              @mklement0 yes .I understood that from the error message,I should have articulated that better in the answer

              – Abhijith pk
              Nov 11 '18 at 4:29
















            Quibble: The reason for the error is that the same file is being targeted twice; PowerShell is perfectly happy to write to a file named write-eventlog, but not via redirections competing for the same output file. Also, I'm not sure that the intent is to write the collected stream output as a single event-log record.

            – mklement0
            Nov 11 '18 at 4:07






            Quibble: The reason for the error is that the same file is being targeted twice; PowerShell is perfectly happy to write to a file named write-eventlog, but not via redirections competing for the same output file. Also, I'm not sure that the intent is to write the collected stream output as a single event-log record.

            – mklement0
            Nov 11 '18 at 4:07





            1




            1





            the problem with this is that it collects all to a variable, and you can do a foreach statement to split out to eventlog later, but I'm trying to write to eventlog in realtime as things are done inside my function

            – ErikW
            Nov 11 '18 at 4:12





            the problem with this is that it collects all to a variable, and you can do a foreach statement to split out to eventlog later, but I'm trying to write to eventlog in realtime as things are done inside my function

            – ErikW
            Nov 11 '18 at 4:12




            1




            1





            @mklement0 yes .I understood that from the error message,I should have articulated that better in the answer

            – Abhijith pk
            Nov 11 '18 at 4:29





            @mklement0 yes .I understood that from the error message,I should have articulated that better in the answer

            – Abhijith pk
            Nov 11 '18 at 4:29

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241825%2fpowershell-cmdlet-how-to-pipe-information-or-error-to-write-eventlog%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

            Crossroads (UK TV series)

            ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế