Reputation: 2216
I am using a function that has an optional switch, however in a loop, switch and related value may be required or not, depending on a pagination mechanism.
# basic function call
myFunction $someParam
# function call with pagination switch
myFunction $someParam -NextPageToken $theToken
Ideally this should be used in a more elegant way in a loop:
$theToken = ""
do{
$result = myFunction $someParam -NextPageToken $theToken # pagination switch should not be used on first call
$theToken = $result.next_page_token
}while($theToken -ne "")
But the function will throw an error if the switch is used with no value....
Does Powershell support dynamically/conditionally adding the switch & value only if required, so that the function call is used only once in code?
Upvotes: 0
Views: 506
Reputation: 174690
Use a hashtable to splat the token:
$params = @{}
do{
$result = myFunction $someParam @params
$params = @{ NextPageToken = $result.next_page_token }
}while("" -ne $params['NextPageToken'])
On the first iteration, the splatting table will be empty (ie. no NextPageToken
parameter will be passed), but subsequent runs will.
See the about_Splatting
help file to learn more about using splatting for conditional parameter arguments
Upvotes: 3