John Ring
John Ring

Reputation: 57

PowerShell Write-EventLog CmdLet works manually, not in script

I am writing a PowerShell script to disable and move users with in AD. this part works great. However I would like to log each event in the event log. The cmdlet Write-EventLog works fine when typed manually.

Write-EventLog –LogName ManageAD –Source “ManageUsers Script” –EntryType Information –EventID 1 –Message “This is a test message"

However, when I add the cmdlet to the script it errors.

Write-EventLog –LogName ManageAD –Source “ManageUsers Script” –EntryType Information –EventID 1 –Message “User ” + $SAM + " has been disabled"

Write-EventLog : A positional parameter cannot be found that accepts argument 'Scriptâ??'.
At C:\test\ManageUsers.ps1:12 char:16
+     Write-EventLog <<<<  â?"LogName ManageAD â?"Source â?oManageUsers Scriptâ?? â?"EntryType Information â?"EventID
 â?"Message â?oUser â?? + $SAM + " has been disabled"
    + CategoryInfo          : InvalidArgument: (:) [Write-EventLog], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteEventLogCommand

Any suggestions are appreciated.

Upvotes: 0

Views: 1289

Answers (1)

Matt
Matt

Reputation: 46700

Want to say the simple answer is you have smart quotes in your code. Those came from where you originally copied that code or a product of your testing environment. Either way you need to watch out for those buggers.

Write-EventLog –LogName ManageAD –Source “ManageUsers Script” –EntryType Information –EventID 1 –Message “User ” + $SAM + " has been disabled"

Should be instead.

Write-EventLog –LogName ManageAD –Source "ManageUsers Script" –EntryType Information –EventID 1 –Message "User " + $SAM + " has been disabled"

I would like to point out from the error that I see other artifacts as well...

â?"LogName ManageAD â?"

It makes me wonder if the hyphens are the long ones like an em-dash (Comes back to an earlier question about your editor choice!).

See the difference subtle here between the hyphen and 2 dashes - – —. Also have your dash against the basic hyphen. The one on the right is the hyphen.

enter image description here

Was the code working inside the ISE maybe and you were running the script in the regular console?

Upvotes: 2

Related Questions