Only pass parameter if value supplied

Question:

Background

I’ve created a wrapper function around Write-EventLog so that I can easily call it without having to concern myself with checking for & creating an event log/source each time. By simply adding a -Force parameter, I want it to create the log if it doesn’t exist; if I don’t add that parameter it should behave as normal (which reduces overhead of multiple checks if called from code where I know that log will exist).

I’ve copied the list of parameters available to write-eventlog such that I have the full functionality available to my wrapper. However; if I don’t supply values to some of these parameters (e.g. RawData), they default to null; then I end up trying to pass null for this parameter; which is different to not supplying it. I don’t want to have to list every possible iteration of parameter combinations with checks for whether those values were supplied before calling the appropriate method signature.

Question

Is there a way to only pass values to parameters of write-eventlog where those parameters had been passed to write-eventlog2?

Code

Error

Answer:

I would consider splatting for something like this as you could account for null / empty without changing too much of the code.

Conditionally build a small hashtable that contains the parameter by name and the value. The use the at sign varialbe notation to splat the Write-Log command. In practice, with Get-ChildItem, if the table contains no pairs or is null it is ignored.

Source:

Only pass parameter if value supplied by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply