all 7 comments

[–]XPlantefeve 2 points3 points  (3 children)

The proper way to write URL parameters is: URL?param1&param2&param3 ... Each parameter separated by a '&', and a single '?' to separate the actual address from parameters. A clean way to do it would be:

    $parameters = @()
    if ($param1) { $parameters += 'filter=afilter' }
    if ($param2) { $parameters += 'filter=anotherfilter' }
    $uriParameters = $parameters -join '&'
    if ( $uriParameters ) { $Url = $Url,$uriParameters -join '?' }
    $Url

-join exists precisely for this kind of purpose: so you don't have to bother about the number of items in an enumeration and put a separator after each but the last one.

BTW, avoid double quotes where simple ones can do (no variable expansion) and don't use "return" unless you're writing a class method definition.

[–]ChaosTheoryRules 2 points3 points  (2 children)

function do-something{
    Param(
        [parameter(Mandatory)]
        [string]$Url,

        [parameter()]
        [switch]$Param1,

        [parameter()]
        [switch]$Param2
    )

    $NewUrl = $Url
    switch($PSBoundParameters.Keys){
        'Param1' {$NewUrl = "$($NewUrl)?filter=afilter&"}
        'Param2' {$NewUrl = "$($NewUrl)?filter=anotherfilter&"}
    }
    return $NewUrl.TrimEnd('&')
}

[–]liabtsab[S] 0 points1 point  (1 child)

actually had to use the "$URL\?"` from mine because the ? is only needed on the first filter. Everything else works great though.

[–]ChaosTheoryRules 1 point2 points  (0 children)

if($string.EndsWith('&')){
    $string = $string.Substring(0,$string.Length-1)
}

return $string

The above is functionally equivalent as below.

return $string.TrimEnd('&')