13

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

name=${UserName:-James}

Does Powershell support something like this?

Chris
  • 28,822
  • 27
  • 83
  • 158
JohnnyLoo
  • 877
  • 1
  • 11
  • 22
  • As a parameter or only as a variable? – Austin T French Aug 25 '16 at 21:51
  • This has a valid answer that is unrelated to the "duplicate" and works for all versions of powershell. The reason it is not a duplicate is because the correct answer is not a valid answer to the duplicate. `$var = Get-VAriable -Name Foo -ValueOnly -scope Global -ea SilentlyContinue || "default_value"` gets the job done. This question should be reopened as it is the best existing question to post this solution to. – Chris Aug 23 '23 at 15:03

1 Answers1

2

Using functions and parameters we can do something like what I believe you are doing.

A function example:

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

calling the function without parameters

WriteUser

will give you the output:

A User

Message

WriteUser -user "Me" -message "Error"

would write the following:

Me

Error

A couple extra notes, you do not have to use the parameter names.

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

You can switch the order of the named parameters as well:

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

and the function will put the to the correct parameter.

Otherwise, I believe you would have to do something to approximate ternary behavior like:

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 function file could also include:

Set-Alias ~ Like-Tern -Option AllScope

And then you would use it like:

$var = ~ $Value : "Johnny"

Of course, ~ was completely arbitrary because I couldn't get ${ to work...

Community
  • 1
  • 1
Austin T French
  • 5,022
  • 1
  • 22
  • 40