PowerTip of the Day-Acessing Function Parameters by Type
原文地址:
http://app.en25.com/e/es.aspx?s=1403&e=5125&elq=52bc48204cc748d58a54ab9a57b6b796
原文:
Adding parameters to your functions is fairly easy. You can add a param() block and specify the parameters. But what if you wanted to assign values to different parameters based solely on type? Let's say you want a function that accepts both numbers and text, and depending on which type you submitted, choose a parameter. Here is how you can do that:
function Test-Binding {
[CmdletBinding(DefaultParameterSetName='Name')]
param(
[Parameter(ParameterSetName='ID', Position=0, Mandatory=$true)]
[Int]
$id,
[Parameter(ParameterSetName='Name', Position=0, Mandatory=$true)]
[String]
$name
)
$set = $PSCmdlet.ParameterSetName
"You selected parameterset $set"
if ($set -eq 'ID') {
"The numeric ID is $id"
} else {
"You entered $name as a name"
}
}
Try this:
Test-Binding 12
Test-Binding "Hello"
Test-Binding
翻译:
方法里添加参数是很简单的。你可以在Param()代码块里添加指定的参数。但是如果想根据参数的类型来选择参数值到底赋给哪个参数呢?假如,有一个方法可以接收两个参数:Numbers和Text,根据你提交的内容,选择哪个参数,以下是实现方法:
function Test-Binding {
[CmdletBinding(DefaultParameterSetName='Name')]
param(
[Parameter(ParameterSetName='ID', Position=0, Mandatory=$true)]
[Int]
$id,
[Parameter(ParameterSetName='Name', Position=0, Mandatory=$true)]
[String]
$name
)
$set = $PSCmdlet.ParameterSetName
"You selected parameterset $set"
if ($set -eq 'ID') {
"The numeric ID is $id"
} else {
"You entered $name as a name"
}
}
调用方法:
Test-Binding 12
Test-Binding "Hello"
Test-Binding
笔记:
这个方法适用于动态参数的赋值,前提是参数的类型必须都不相同,否则会有歧义。
---------------------------------------------------------------
aspnetx的BI笔记系列索引:
使用SQL Server Analysis Services数据挖掘的关联规则实现商品推荐功能
---------------------------------------------------------------
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步