How to Use PowerShell to Write to Event Logs

Summary: Guest blogger, Jonathan Tyler, talks about how to write to Windows event logs by using Windows PowerShell—and avoid errors in doing so.

Microsoft Scripting Guy, Ed Wilson, is here. While I was at TechEd in New Orleans, I had the chance to talk to Jonathan Tyler. I see him from time-to-time, although he only lives a few hours away from us. Jonathan is an active member of the Windows PowerShell community, and he has written other posts for the Hey, Scripting Guy! Blog.

I am happy to welcome back guest blogger, Jonathan Tyler…

Let’s start with a poll. How many of you like to get feedback from your Windows PowerShell scripts, either by a verbose switch or in some sort of log file? Great, you can put your hands down. Now, how many of you like to get feedback from a script that you have running as a scheduled task? And now, how many simply write to a text file or simply forget about getting feedback unless you find that there is a problem?

By the end of this post, I will show you how you can leverage the premier logging system on any Windows Server: the event log! If you work in an enterprise, you most likely have some type of central monitoring system that collects errors from your event logs. Why not use that same system to capture and report when one of your Windows PowerShell scripts goes wrong? The best thing is that you don’t even have to stick to errors.

To begin with, let’s flip over to the Windows PowerShell console and see what cmdlets are available that deal with the event logs.

Image of command output

It looks like the one we probably need is Write-EventLog. To try this out, I am going to write a test message to the Application event log. This should be fairly straightforward:

Write-EventLog –LogName Application –Source “My Script” –EntryType Information –EventID 1
 –Message “This is a test message.”

In this command, the LogName, Source, EventID, and Message are required parameters. After running this command, I would expect a new message to show up in the Application event log. Run this on your computer and then check the event logs. I’ll wait…

What? You got an error message? I’m betting it is because your computer doesn’t have a source called “My Script.”

Image of error message

Note   If you received a slightly different error that states not all event logs (Security) could be scanned, you need to run Windows PowerShell as an Administrator. I will explain a little more about this later.

So, how in the world can we use the event log if we have to have a Source parameter but the source we want to use is not on the server? If you look back at the first screenshot, you will see another cmdlet in the list that will help us out: New-EventLog.

The New-EventLog cmdlet can be used not only to create a brand new event log on the computer, but it can also create a new source that can be used when you write to the event log. I have actually used this in some instances for custom code in a SharePoint farm. The custom code being deployed needed to write information to the event logs, but the application pool account did not have the administrative rights to create the source. Instead of elevating the application pool’s rights on all the servers, I used this cmdlet to create a new source, and then the custom code was happy to report to the event logs.

To fix our previous error, we can use the following line as an Administrator on the computer:

New-EventLog –LogName Application –Source “My Script”

Image of command output

As you can see, the Write-EventLog now returns with no error. And if we check the event log entries, we should now see our test message.

Image of event log

And the details of the message:

Image of message

As you can see, the source is now populated with “My Script.”

To create a new source for an event log, administrative privileges are required. But the nice thing is that you only have to do this once for the source. When it is installed on the computer, you don’t have to worry about it again. Additionally, you can leverage Windows PowerShell to make the change across multiple machines by supplying the ComputerName parameter. You can also use this to create an event log specifically for your script or to create a source for event logs other than the Application log.


Thank you, Jonathan, for sharing your time and knowledge with us today. Hopefully, it will not be another year before I get to see you again.

Join me tomorrow when I have another guest blog by Honorary Scripting Guy and Microsoft PowerShell MVP, Sean Kearney, as he continues his series about using Windows PowerShell with Hyper-V. It is cool stuff and you do not want to miss it.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

Comments (26)

  1. Jonathan – this came in handy for me this morning. Thanks for the post!

  2. Anonymous says:

    Hi Jonathan,

    Nice script ,Can you also help to show PowerShell script for writing Error log in Event Log.
    e.g. instead of of level ‘Information’ ,log will add as Type: Error in event logs

  3. Really useful stuff, thanks.  I'm looking forward to dumping my error variables into a new event log.

  4. Anonymous says:

    @IamMred Thanks for the opportunity.  I enjoyed writing it.

  5. K_Schulte says:

    Hi Jonathan,

    thank you for your information about event logs!

    We can create new event logs and write to them very easily using Powershell.

    Reporting progress, errors or information that way, especially in background jobs, is a great idea!

    btw: There is a minor typo "Write-EevntLog" instead of "Write-EventLog" in :

    Write-EevntLog –LogName Application –Source “My Script” –EntryType Information –EventID 1

    –Message “This is a test message.”



  6. mredwilson says:

    @K_Schulte @Jonathan Tyler @Typo Alert I just fixed the typo. Everything should be groovy now. Thank you for pointing this out.

    @Jonathan dude you rock. Awesome job again on the article.

  7. Anonymous says:

    Typo has been noted. Trying to get it corrected. Thanks

  8. Jeff Wouters says:

    Hi Jonathan,

    Nice post, thank you for sharing.

    In large(r) scripts you way want to create a small function you can call to write to the eventlog:…/use-powershell-to-write-to-the-event-log

    Keep on sharing, happy to read more from your hand 🙂


  9. Jonathan Tyler says:

    @Klaus Thanks for the heads-up on the typo.  Too bad I can't blame auto-correct on a phone for that one! 🙂  Anyways, I have reached out to try to get it corrected.  Glad you found the article helpful.

    @Jeff I absolutely agree with creating a small function to handle the logging.  You could create a function that can log information to the screen (pending verbose/debug settings) as well as to the event log in one call.  Thanks for the comment!

  10. Typo Alert... says:

    FYI: Just under the listing to "see what cmdlets are available that deal with the event logs", the first code example starts with the command, "Write-EevntLog".  Should that actually be "Write-EventLog"?

  11. ML49448 says:

    Anyone tried to combine this with Start-Transcript to record the items in the Message field of the commands executed?

  12. Surender says:

    Hey! Scripting Guy,

    I am very thankful to you as your posts help me to learn a lot about Windows Powershell. I am new to Powershell and do not know much about powershell scripting yet but you really rock man!!!


  13. NikolaB says:

    Hi, i have txt file that is log file from my app and i nead to create Log in EventLog, for example in application.

    txt file is like

    5.11.2013 14:29:46 — Uspešno potvrdjena otpremnica 240201300001 — 000003.XML

    11.11.2013 14:14:56 — Nije potvrdjena otpremnica 240201300072 — 000009.XML

    11.11.2013 14:14:58 — Nije pronadjena otpremnica -23363947    iz fajla 000008.XML u UPIS-u!

    11.11.2013 14:14:58 — Nije pronadjena otpremnica -23366575    iz fajla 000008.XML u UPIS-u!

    11.11.2013 14:14:58 — Nije pronadjena otpremnica -23364064    iz fajla 000008.XML u UPIS-u!

    and for each time (5.11.2013 14:29:46) have to create one log, but

    error is "11.11.2013 14:14:56 — Nije potvrdjena otpremnica 240201300072 — 000009.XML "

    and information is "5.11.2013 14:29:46 — Uspešno potvrdjena otpremnica 240201300001 — 000003.XML "

  14. Bill Foster says:

    Ed you and the PowerShell team are awesome. I needed a quick way to write events to the event log and you didn't disappoint.

  15. Jeff25 says:

    Great article.  

    One item that might be a nice potential add:

    A command to test if you need to execute the new-eventlog command.  The following can be ran prior to a New-Eventlog command using the "LogName" and "Source" used in your post.  The command goes well in a script/function to test if you need to create a new source prior to adding an event associated with it.  This way you'll be able to run (and rerun) the associated script/funciton without any provisioning of a system ahead of time:

    if (!(Get-Eventlog -LogName "Application" -Source "MyScript")){

         New-Eventlog -LogName "Application" -Source "MyScript"




  16. Andrew says:

    I found the following was a lot more efficient when the source doesn't exist:


  17. Ben says:

    Pretty crazy that you have to be an Administrator to add an event source, which means you can’t really write an event for your own source if it doesn’t exist. Limiting.

  18. Oliver says:

    Nice Post, I do however have a problem with the way the commands work.
    The ability to check if a EventLog exists seems to be a strangly difficult.

    Get-EventLog fails if log does not exist or if it has no events.
    New-EventLog fails is one already exists.

    Between these two behaviors it is not easy to check if an EventLog exists before trying to create one.
    Almost a chicken/egg problem.

    Ideally, New-EventLog should do nothing if the log+source already exists. That way one can call a single function, especially useful when automating deployments.

  19. bot27 says: Часы и бегущие строки оптом и в розницу Завод входных и противопожарных дверей Витязь панели МДФ и ОСП оптом с Китая Металлические двери в Хабаровске

    http://ворота Hormann-Официальный дилер в Южно-Сахалинске

    http://хабаровсктара.рф Производство туалетной бумаги, салфеток в Хабаровске Магазин офисной мебели и радиаторов отопления КомЭконом г. Хабаровск Создание и продвижение сайтов в Хабаровске. ДВ Гид Хостинг для микросайтов: одностраничников, лендингов, визиток Медицинский центр ООО"Бэст-Мед" Cтудия художественной ковки с Хабаровске "Хёрманн" Официальный дистрибьютор Роллсервис в Хабаровске Пансионат для пожилых людей Благо г. Хабаровск Всё для отопления, водоснабжения, канализации

    http://спецавтотранс-дв.рф Современные методы восстановления инженерных коммуникаций

    http://вавилон-дв.рф Поставка горно-рудного, дробильно-сортировочного оборудования, спецтехники, конвейеров,

    грохот, экскаваторы, а также комплектующие и расходные материалы для спецтехники в Хабаровске Продажа видеорегистраторов и камер видеонаблюдения Интерьерно-строительная компания "Город Золотой" г. Хабаровск Компания Инженерные системы в Хабаровске Автокомплекс Колесница г. Хабаровск Бухгалтерские услуги Электромонтажные работы в Хабаровске

    http://генетика-дв.рф Медико-генетический центр г. Хабаровск

    http://литале.рф Салон красоты – ЛиТаЛе г. Хабаровск

    http://хабаровская-коллегия-адвокатов.рф Хабаровская коллегия адвокатов Малоэтажное строительство и ремонт под ключ Строительство автодорог, благоустройство, малоэтажное строительство,

    аренда спецтехники, аренда самосвалов, перевозка сыпучих материалов в Хабаровске Мебельный центр "Мегаполис" г. Хабаровск Магазин канцелярских товаров Ластиково г. Хабаровск

    http://платье Салон свадебной и вечерней моды "Анастасия" Детский мед. центр салон красоты Компания Запас Прочности.
    Продажа грузоподъемного, нефтегазового,
    сварочного оборудования во Владивостоке и Хабаровске

  20. Kristian says:

    I’ve looked all over – but I cannot seem to get the information about creating a new eventlog in a sub folder – or creating the folder – any tips for this will be appreciated.

    I tried ‘new-eventlog -source someSource -logname companyeventlog’ – but the nice blue screen does not allow the ” when I tried using the / instead – the resulting eventlog would simply be named "company/eventlog".

    How can I accomplish this?

  21. WyattWong says:

    How to I insert a new line character to the Message when I want to write multiple lines ? I found adding rn doesn’t work as expected.

  22. WyattWong says:

    I found the solution to write multiple lines of Message using PowerShell Write-EventLog command after checking the following URL:

    First create an empty $MessageArr variable and assign the line of text into it. Note the use of the += operator to append each line into the $MessageArr variable. After that, convert the $MessageArr into $Message of string type.

    Finally, pass the $Message variable to the -Message parameter of Write-EventLog command.

    $MessageArr = @()
    $MessageArr += "Text1"
    $MessageArr += "Text2"
    $MessageArr += "Text3"
    $Message = $MessageArr | Out-String

    Write-EventLog -LogName Application -Source "My Script" -EntryType Information -EventID 1 -Message $Message -Category 0

    1. kheg says:

      ahh this works well. i can string verubles this way.
      the other u noted i could not get it work.

  23. Wyatt says:

    I found a even more simple way to insert newline character using Write-EventLog command by using a `n where ` is the back quote character.

    Write-EventLog -LogName Application -Source "My Script" -EntryType Information -EventID 1 -Message "Text1`nText2" -Category 0

    Using the above command, the Text1 and Text2 are shown in separate line in the Application Event Log.

  24. Hooman says:

    Thank you 🙂

  25. Henrik says:

    $Sourcename = “Henrik is cool”
    if (!([System.Diagnostics.EventLog]::SourceExists($Sourcename))){
    New-EventLog –LogName Application –Source $Sourcename
    #random messages:
    Write-EventLog –LogName Application –Source $Sourcename –EntryType Information –EventID 1337 –Message “Is still the coolest” -Category 0
    Write-EventLog –LogName Application –Source $Sourcename –EntryType Warning –EventID 31337 –Message “Coolness is low`nDo something about it`nGet cooler now” -Category 0
    Write-EventLog –LogName Application –Source $Sourcename –EntryType Error –EventID 9000 –Message “Not cool at all, will need moar coolness” -Category 0

Skip to main content