0

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?

1
  • Does not sound like a good function design. Let it return the first token when "" is passed to -NextPageToken or don't use any parameter and just let it return the next token (works only if you don't need to go back). Commented May 20, 2020 at 10:13

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Stylish!......... Thanks :-) . Just a question: in your sample, is it intentional to use NextPageToken in place of -NextPageToken ?
@Riccardo Yes that's intentional - the hashtable key must match the name of the parameter - and the - we use in normal command syntax is not part of the name itself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.