传递可选参数 [英] Passing an optional parameter

查看:134
本文介绍了传递可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆