如何在 powershell 的 param 函数中使用变量?

How to I use variables in the param function in powershell?

我不确定这是否可行,但我想尝试一下。

这是我正在尝试做的事情的基础:

function somefunction () {
    $ListOfItems = (get-childitem c:\).name
    param (
        [validateset($ListOfItems)][string]$Moo
    )
}

我不知道一个变量是否可以在validateset中使用。看起来不是这样。如果可以的话,我将如何去做呢?

阅读评论并根据评论完成研究后,我相信没有简单的方法可以做我想让它做的事。

这是可行的。你在追求 ValidateScript

Function somefunction () {
    param (
        [ValidateScript({$_ -in (Get-Childitem C:\).Name})] 
        [string]$Moo
    )
}

编辑
ValidateScript 的默认错误不是用户友好的:

PS C:\> somefunction -Moo thing

somefunction : Cannot validate argument on parameter 'Moo'. The "$_ -in (Get-Childitem C:).Name" validation script for the argument with value "thing" did not return a result of True. Determine why the validation script failed, and then try the command again.

This Whosebug post goes over how to generate custom error messages