Function overloading in PowerShell

前端 未结 4 1669
温柔的废话
温柔的废话 2020-12-15 16:11

Can you overload functions in PowerShell?

I want to my function to accept a string, array or some switch.

An example of what I want:

  • Backup-Use
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 16:38

    Here is a variant of Roman's answer that I think is a little more flexible:

    function Backup
    {
        [CmdletBinding(DefaultParameterSetName='Users')]
        Param (
            [parameter(mandatory=$true, ParameterSetName='Users', position=0, ValueFromPipeline=$true)][string[]]$User,
            [parameter(mandatory=$true, ParameterSetName='AllUsers')][switch]$All
        )
    
        Begin
        {
            if ($All) { $User = @('User1', 'User2', 'User3') }
        }
    
        Process
        {
            foreach ($u in $User)
            {
                echo "Backup $u"
            }
        }
    }
    

提交回复
热议问题