Passing an optional parameter

I have a PowerShell script CSV2JSON.ps1with the following code:

param(
        [String]$FieldSeparator=",",
        [String[]]$Header
)

$input | ConvertFrom-Csv -Delimiter $FieldSeparator -Header $Header | ConvertTo-JSON

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

ConvertFrom-Csv : Cannot validate argument on parameter 'Header'.
The argument is null. Supply a non-null argument and try the command again.

I do not want to pass the parameter -Headerat all if it is not specified. Is there a neat way to pass optional parameters without going into instructions If?

+4
source share
4 answers

I am surprised that no one suggested splatting an automatic variable $PSBoundParameters.

$PSBoundParameters - a hash table containing all the arguments of the parameters that were passed to the command.

$FieldSeparator $Delimiter, . FieldSeparator , :

param(
        [Alias('FieldSeparator')]
        [String]$Delimiter=",",
        [String[]]$Header
)

$input | ConvertFrom-Csv @PSBoundParameters | ConvertTo-JSON

-Header /script, ConvertFrom-Csv

+5
, if, splatting, :
param(
        [String]$FieldSeparator=",",
        [String[]]$Header
)

$params = @{
    Delimeter = $FieldSeparator
}
if ($Header) {
    $params.Header = $Header
}

$input | ConvertFrom-Csv @params | ConvertTo-JSON
+2

. if. , :

param(
        [String]$FieldSeparator=",",
        [String[]]$Header,
        [switch]$Compress        
)

$input | ConvertFrom-Csv -Delimiter $FieldSeparator | ConvertTo-JSON -Compress:$Compress

. MyInvocation.BoundParameter splatting, , script .

+1
source

Ok, I have another option based on Martin's feedback. This works well when the parameter names match:

param(
    $Path,
    $Delimiter,
    $Header
)

$params = @{}
$MyInvocation.BoundParameters.Keys | Where {$_} |
    % {$params.Add($_, (Get-Variable $_).Value )}

Import-Csv @params
0
source

Source: https://habr.com/ru/post/1660505/


All Articles