Skip to content

Instantly share code, notes, and snippets.

@fgimian
Created June 5, 2019 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgimian/09dbcee04e7bee37ae331ad1f04e519f to your computer and use it in GitHub Desktop.
Save fgimian/09dbcee04e7bee37ae331ad1f04e519f to your computer and use it in GitHub Desktop.
How can I allow parameter sets to be optional? :)
function Install-File {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, Position=0)][string]$Path,
[Parameter(ParameterSetName='SourcePath')][string]$SourcePath,
[Parameter(ParameterSetName='Content')][string]$Content,
[Parameter(ParameterSetName='DownloadUrl')][string]$DownloadUrl
)
# ...
}
# Valid inputs
Install-File -Path C:\myfile.txt # QUESTION: How can I allow this scenario to be accepted?
Install-File -Path C:\myfile.txt -SourcePath C:\source.txt
Install-File -Path C:\myfile.txt -Content hello
Install-File -Path C:\myfile.txt -DownloadUrl http://myfile.txt
@adrian-andersson
Copy link

adrian-andersson commented Jun 5, 2019

function Install-File {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, Position=0,ParameterSetName='Default')]
        [Parameter(Mandatory=$true, Position=0,ParameterSetName='SourcePath')]
        [Parameter(Mandatory=$true, Position=0,ParameterSetName='Content')]
        [Parameter(Mandatory=$true, Position=0,ParameterSetName='DownloadUrl')]
        [string]$Path,
        [Parameter(ParameterSetName='SourcePath')]
        [string]$SourcePath,
        [Parameter(ParameterSetName='Content')]
        [string]$Content,
        [Parameter(ParameterSetName='DownloadUrl')]
        [string]$DownloadUrl
    )

    # ...\
    if($sourcePath)
    {
        write-host 'SourcePath'
    }elseIf($content)
    {
        write-host 'Content'
    }elseIf($DownloadUrl)
    {
        write-host 'DownloadUrlCode'
    }else{
        write-host 'Use something else'
    }

}

# Valid inputs
Install-File -Path C:\myfile.txt  # QUESTION: How can I allow this scenario to be accepted?
Install-File -Path C:\myfile.txt -SourcePath C:\source.txt
Install-File -Path C:\myfile.txt -Content hello
Install-File -Path C:\myfile.txt -DownloadUrl http://myfile.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment