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()代码块里添加指定的参数。但是如果想根据参数的类型来选择参数值到底赋给哪个参数呢?假如,有一个方法可以接收两个参数:NumbersText,根据你提交的内容,选择哪个参数,以下是实现方法:

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

 

 

笔记:

这个方法适用于动态参数的赋值,前提是参数的类型必须都不相同,否则会有歧义。

posted @ 2010-06-30 18:12  哥本哈士奇(aspnetx)  阅读(350)  评论(0编辑  收藏  举报