【问题标题】:powershell Call method with optional arguments带有可选参数的powershell调用方法
【发布时间】:2013-07-03 05:42:51
【问题描述】:

我有一个在工作表中查找特定单元格的 excel vba 代码。它使用 excel 库中的 Find 方法。这是代码

objRange.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows)

我需要在 powershell 中做同样的事情。但是这个方法总共有 9 个参数。如何忽略 powershell 中的其他可选参数。像这样?

$range.Find("*", "", "", "", $xlByRows, $xlPrevious, "", "", "")

HereRange.Find方法的文档

【问题讨论】:

    标签: powershell parameter-passing


    【解决方案1】:

    $null不起作用,但是根据this answer可以使用[Type]::Missing

    $default = [Type]::Missing
    $xl.Cells.Find("*", $default, $default, $default, $xlByRows, $xlPrevious,
                   $default, $default, $default)
    

    【讨论】:

    • 必须有某种方式为不需要的参数提供默认值
    • @Ammar,如果能找到一种仅命名您关心的可选值的方法,类似于 VBA := 语法,那么幸运吗?
    • @Jay,我刚刚使用了Ansgar提供的解决方案。
    • @Jay,根据stackoverflow.com/questions/24520664/…,这可能是不可能的。
    • @irh 是的,这种事情需要语言中内置的实际语法。我倾向于认为如果可以做到的话,我们会看到如何做到这一点的例子。可能有一种方法可以为我构建一个 FunctionWithOptionalArgumentCaller 类。也许它可以使用反射来找出可选的类型和默认值,并公开一种方法来设置我关心的那些。不过似乎不值得。
    【解决方案2】:

    我通过创建使用我想要的值调用核心方法的重载方法来解决这个问题。例如我希望用户能够指定处理记录的数量或调用“增量”方法,然后只调用“WriteProgress”而不带参数:

    class UserFeedback {
    [string]$Name
    [int]$ThingCount
    [datetime]$ProcessStartDateTime
    [int]$ProcessedCount
    
    UserFeedback ([string] $Name,[int]$ThingCount){
        $this.ProcessStartDateTime = Get-Date
        $this.Name = $Name
        $this.ThingCount = $ThingCount
        $this.ProcessedCount = 0
    }
    
    WriteProgress([int] $intProcessed){
        $this.ProcessStartDateTime        
        $SecondsElapsed = ((Get-Date) - $this.ProcessStartDateTime).TotalSeconds
        $SecondsRemaining = ($SecondsElapsed / ($intProcessed / $this.ThingCount)) - $SecondsElapsed
        Write-Progress -Activity $this.Name -PercentComplete (($intProcessed/$($this.ThingCount)) * 100) -CurrentOperation "$("{0:N2}" -f ((($intProcessed/$($this.ThingCount)) * 100),2))% Complete" -SecondsRemaining $SecondsRemaining
    }
    
    WriteProgress(){
        $this.WriteProgress($this.ProcessedCount)
    }
    
    Increment(){
        $this.ProcessedCount ++    
    }
    

    }

    【讨论】:

    • 老方法是最好的方法,一个比其他方法更优雅的好实用的解决方案——感谢提醒
    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 2011-01-26
    • 1970-01-01
    • 2013-08-11
    • 2014-08-22
    • 2016-12-15
    • 1970-01-01
    相关资源
    最近更新 更多