2

Probably the most basic question ever. But I don't code much and I'm trying to execute this powershell script with my params but I'm not even sure where i put them. For instance, in the below, if I want to put my username value - where do I place it? Do I change the "$UserName" param to $Mydesiredusername. Or do I place my username next to the variable name, like a key value pair, such as this, "$UserName, myusername"?

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    $UserName,

    [Parameter(Mandatory=$true)]
    $BaseBranch, 

    [Parameter(Mandatory=$true)]
    $Branches,

    [Parameter(Mandatory=$true)]
    $FilePath,
2
  • Can you edit your question to remove the image and instead paste the code in directly? Commented Feb 26, 2020 at 17:38
  • will do. charss Maybe it needs to be $UserName = myusername?? Commented Feb 26, 2020 at 17:39

1 Answer 1

1

So based on your provided, code, I can see four parameters to your script/cmdlet (Advanced Parameters work the same either way, for simplicity I'll assume this is a script for this answer).

  • UserName
  • BaseBranch
  • Branches
  • FilePath

These get invoked like so:

./Script.ps1 -UserName 'username' -BaseBranch 'branchName' -Branches 'branchNames' -FilePath '\path\to\file.ext'

If you want a default value to be provided for that parameter, assign the parameter variable a value. This value is only used if the user calling the script doesn't provide the parameter value. For example:

$UserName = 'defaultUserName',

Advanced Parameters are basically regular variables that have special assignment rules (which you can customize the behavior of with parameter attributes) since they are provided when invoking the script or function.

Also, when you have a parameter with a default value assigned you do not need to make the parameter mandatory.


Additionally, consider giving your -Branches parameter a type of [string[]], like this:

[string[]]$Branches,

This will allow you to invoke the parameter more conveniently, and not have to parse the string in your script. Note that you can provide a single element or multiple:

./Script.ps1 -Branches branch1, branch2, branchX
./Script.ps1 -Branches branchX

Instead of:

./Script.ps1 -Branches 'branch1,branch2,branchX'

While either approach will work, string parsing can bring with it its own set of issues (such as escaping the delimiter if it occurs within a value), and providing multiple values to a parameter as an array is the idiomatic approach in PowerShell.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.