2017-09-25 88 views
0

我想创建log功能的工作方式类似于Write-Host,我可以给它特设的参数与一些参数一起:功能的优先级为未申报的参数在声明

function log ([int]$ident=0, [switch]$notime) { 

    $now = (Get-Date).ToString('s') 

    Write-Host $(if (!$NoTime) {now}) $($args | % { ' '*$ident*2 + $_ }) 
} 



log 'test 1' 'test 2' # Cannot convert value "test 1" to type "System.Int32" 
log 'test 1' 'test 2' -Ident 1 #Works 

我知道我可以获取未声明的参数$args或使用ValueFromRemainingArguments属性,但这要求我改变调用函数的方式,因为声明的函数参数将收集它们。

回答

4

关闭位置结合:

function log { 
    [CmdletBinding(PositionalBinding=$False)] 
    param (
     [int]$indent=0, 
     [switch]$notime, 

     [Parameter(ValueFromRemainingArguments)] 
     [string[]] $rest 
    ) 

    $now = (Get-Date).ToString('s') 

    Write-Host $(if (!$NoTime) {$now}) $($rest | % { ' '*$indent*2 + $_ }) 
} 

需要注意的是,很明显,你现在需要包括参数的名称,但应该是(它会被混淆到要知道是否好东西1indent的值或记录的第一个值)。

+0

不知道'PositionalBinding'。谢谢一堆。 – majkinetor

相关问题