传递可选参数 [英] Passing an optional parameter
问题描述
我有一个PowerShell脚本CSV2JSON.ps1
,其中包含以下代码:
I have a PowerShell script CSV2JSON.ps1
with the following code:
param(
[String]$FieldSeparator=",",
[String[]]$Header
)
$input | ConvertFrom-Csv -Delimiter $FieldSeparator -Header $Header | ConvertTo-JSON
如果我将其称为.\CSV2JSON.ps1 -FieldSeparator "|" -Header "name|age"
,则可以正常工作.但是,如果删除可选参数Header
,则ConvertFrom-Csv
cmdlet抱怨Header
不能为null:
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:
ConvertFrom-Csv : Cannot validate argument on parameter 'Header'.
The argument is null. Supply a non-null argument and try the command again.
我根本不想传递-Header
参数(如果未提供).有没有一种精巧的方法来传递可选参数而无需进入If
语句?
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
是一个哈希表,其中包含传递给命令的所有参数实参.
$PSBoundParameters
is a hashtable containing all the parameter arguments that was passed to the command.
只需将$FieldSeparator
参数重命名为$Delimiter
,就可以了.
如果需要,可以提供FieldSeparator
名称作为参数别名:
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:
param(
[Alias('FieldSeparator')]
[String]$Delimiter=",",
[String[]]$Header
)
$input | ConvertFrom-Csv @PSBoundParameters | ConvertTo-JSON
如果在执行调用函数/脚本时省略了-Header
参数,则在调用ConvertFrom-Csv
If the -Header
parameter is omitted when executing the calling function/script, it'll also be omitted from the call to ConvertFrom-Csv
这篇关于传递可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!