Question:
I have a PowerShell script CSV2JSON.ps1
with the following code:
1 2 3 4 5 6 7 |
param( [String]$FieldSeparator=",", [String[]]$Header ) $input | ConvertFrom-Csv -Delimiter $FieldSeparator -Header $Header | ConvertTo-JSON |
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:
1 2 3 |
ConvertFrom-Csv : Cannot validate argument on parameter 'Header'. The argument is null. Supply a non-null argument and try the command again. |
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?
Answer:
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:
1 2 3 4 5 6 7 8 |
param( [Alias('FieldSeparator')] [String]$Delimiter=",", [String[]]$Header ) $input | ConvertFrom-Csv @PSBoundParameters | ConvertTo-JSON |
If the -Header
parameter is omitted when executing the calling function/script, it’ll also be omitted from the call to ConvertFrom-Csv