Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Write-EventLog from a command line using a variable for -Message

$
0
0

My apologies for the possibly confusing title of this post, so let me explain...

My ultimate goal is to capture log information during the execution of a batch script and write it to the Application log.  Simple, you might think?  I couldn't figure it out in batch so gave up and moved on to try using PowerShell via the @powershell command.

I started with the following test, which worked like a charm:

@PowerShell -NoProfile -command "Write-EventLog -LogName Application -Source MyApp -EntryType Information -EventID 99 -Message "Test1" -ComputerName MyServer"

Great I thought, now how to capture multiple "events" as my batch script executes so that I can write them all in one go to the Application log using a single @powershell command.  Capturing multiple lines of text in an environment variable was a struggle and I wasn't even sure if I could then use the environment variable in the PowerShell command, so I tried writing the events to a text file with the intend of reading that text file using Get-Content, and then writing it to the event log.

So test #2 went like this:

@PowerShell -NoProfile -command "$OutText = 'Some text';Write-EventLog -LogName Application -Source MyApp -EntryType Information -EventID 99 -Message $OutText -ComputerName MyServer"

This worked, and "Some text" was successfully written to the event log entry, so the last step was to read my entries from the text file and write them instead:

For reference, the text file looked like this:

Test Entry 1
Test Entry 2
Test Entry 3 

@PowerShell -NoProfile -command "$OutText = Get-Content .\TestLog.txt;Write-EventLog -LogName Application -Source MyApp -EntryType Information -EventID 99 -Message $OutText -ComputerName MyServer"

Unfortunately I failed at the last hurdle as PowerShell didn't seem to like, I am guessing, the CRLFs in the text file?

Write-EventLog : Cannot convert 'System.Object[]' to the type 'System.String'
required by parameter 'Message'. Specified method is not supported.
At line:1 char:211
+ ... yServer -Message $OutText
+                    ~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Write-EventLog], Parameter
   BindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Comma
   nds.WriteEventLogCommand

Any suggestions on how to solve my dilemma, either by solving the last step, or maybe by taking a different approach?

Many thanks, in advance,
Andy


Viewing all articles
Browse latest Browse all 15028

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>