Set default value for variable in Powershell

In bash, I can do something like this to set name to the default value if UserName not set:

 name=${UserName:-James} 

Does Powershell support something like this?

+6
source share
1 answer

Using functions and parameters, we can do something like what you think you are doing.

Function example:

 function WriteUser { param($user = "A User", $message = "Message") Write-Host $user Write-Host $message } 

function call without parameters

 WriteUser 

will give you the result:

User

Message

WriteUser -user "Me" -message "Error"

will write the following:

Me

Error

A few additional notes, you do not need to use parameter names.

 WriteUser "Bob" "All Systems Go" would work by the order of the parameters. 

You can also change the order of named parameters:

 WriteUser -message "Error" -user "user, user" 

and the function will return the correct parameter.

Otherwise, I suppose you will need to do something to get closer to ternary behavior, for example:

 function Like-Tern { for ($i = 1; $i -lt $args.Count; $i++) { if ($args[$i] -eq ":") { $coord = $i break } } if ($coord -eq 0) { throw new System.Exception "No operator!" } $toReturn if ($args[$coord - 1] -eq "") { $toReturn = $args[$coord + 1] } else { $toReturn = $args[$coord -1] } return $toReturn } 

Credit for the idea here. A functional file may also include:

 Set-Alias ~ Like-Tern -Option AllScope 

And then you will use it like:

 $var = ~ $Value : "Johnny" 

Of course ~ was completely arbitrary, because I could not get ${ to work ...

+1
source

All Articles