Using argument or default values in PowerShell Script

Welcome Forums General PowerShell Q&A Using argument or default values in PowerShell Script

Viewing 3 reply threads
  • Author
    Posts
    • #256403
      Participant
      Topics: 2
      Replies: 2
      Points: 26
      Rank: Member

      Hi,

      I want my PowerShell script to use five variable values that the user will enter but if there is no value provided by the user, than it should take the default values that I would provide for those variables at the beginning.
      What is the best approach to do this?

      Thank you

    • #256406
      Participant
      Topics: 25
      Replies: 206
      Points: 771
      Helping Hand
      Rank: Major Contributor

      Should be able to add something like below at the top of your script.

      Param
      (
      [string]$param1 = “some default value”,
      [string]$param2 = “some default value”,
      [string]$param3 = “some default value”,
      [string]$param4 = “some default value”,
      [string]$param4 = “some default value”
      )

    • #256415
      Participant
      Topics: 2
      Replies: 2
      Points: 26
      Rank: Member

      Yes, this is for setting up the default values. But firstly I need to check if the user enters values for these variables.
      If it does, than we should use the values that the user has entered. If there are no values provided, than the default ones.

    • #256421
      Participant
      Topics: 8
      Replies: 669
      Points: 2,631
      Helping Hand
      Rank: Community Hero

      That’s exactly how the parameter binder works. David’s example is exactly what you described. If the user provides any of those individually, those values will be used.. otherwise the default values will be used. You would be duplicating work already handled by powershell. Maybe this example will help illustrate.

      When called without providing values as shown, the output is

      If you provide 1 or all with values, they will be used instead

Viewing 3 reply threads
  • You must be logged in to reply to this topic.