Passing an optional parameter


I have a PowerShell script CSV2JSON.ps1 with the following code:

If I call it as .\CSV2JSON.ps1 -FieldSeparator "|" -Header "name|age" it works fine. However, if I drop the optional parameter Header, the ConvertFrom-Csv cmdlet complains that Header cannot be null:

I don’t want to pass the -Header parameter at all, if it’s not provided. Is there a neat way to pass on optional parameters without getting into If statements?


I’m surprised no one has suggested splatting the $PSBoundParameters automatic variable.

$PSBoundParameters is a hashtable containing all the parameter arguments that was passed to the command.

Simply rename the $FieldSeparator parameter to $Delimiter and you’re good to go.
You can provide the FieldSeparator name as a parameter alias if needed:

If the -Header parameter is omitted when executing the calling function/script, it’ll also be omitted from the call to ConvertFrom-Csv


Passing an optional parameter by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply