首页 > 解决方案 > 如何在 powershell 脚本中使用动态参数,而不是函数

问题描述

我正在尝试在我的 powershell 脚本中获取一些动态验证集,例如

MyScript.ps1 -Parameter1 DynamicAttributeDefinedWithinRuntime

我找到的所有帮助都是针对 PowerShell 函数中的动态参数,例如

MyPowerShellFunction -Parameter1 DynamicAttributeDefinedWithinRuntime

如果我在脚本中使用动态参数创建一个函数,当从 powershell 窗口执行脚本文件时,我可以在 CLI 中使用这些函数吗?

标签: powershell

解决方案


这是一个很棒的参数教程Dynamic ValidateSethttps ://vexx32.github.io/2018/11/29/Dynamic-ValidateSet/

该站点的一种方法是使用第二个功能:

function Get-ValidValues {
    [CmdletBinding()]
    param($Path)

    (Get-ChildItem -Path $Path -File).Name
}

function Clear-FileInCurrentLocation {
    <#
    .synopsis
        Dynamic ValidateSet from: https://vexx32.github.io/2018/11/29/Dynamic-ValidateSet/
    #>
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [Parameter(Position = 0, Mandatory)]
        [ArgumentCompleter(
            {
                param($Command, $Parameter, $WordToComplete, $CommandAst, $FakeBoundParams)
                Get-ValidValues -Path (Get-Location)
            }
        )]
        [ValidateScript(
            {
                $_ -in (Get-ValidValues -Path (Get-Location))
            }
        )]
        [string]
        $Path
    )

    Clear-Content -Path $Path
}

推荐阅读