Assign Default Values to PowerShell Variables: Both Literals and Expressions.

Pavol Kutaj
1 min readJul 15, 2021

--

The aim of this playbookšŸ is to demonstrate the assignment of a default value to a variable of a powershell function. For comparison in Python you do the assignment within parameter declaration:

def foo(bar="xxx"):
print(bar)
foo()
>>> xxx

1. answer

  • for shorthanded style, identical to pythonā€™s syntax
  • just assign the default value to the parameter: function foo($t = "bar") {write-host $t}
foo
> "bar"
  • for long-handed style, use param keyword
  • put the the $paramName = defaultValue into parenthesis right after the code block begins
  • use function <funcName> {param($foo = <defaultValue>) <code>}
  • see example2 for an expression as a default value

2. default value as literal

function start-writing {
param($len = 1)
$url = "https://www.squibler.io/dangerous-writing-prompt-app/write?limit=$len&type=minutes"
start chrome $url
}

3. default value as an expression

Function rdbl {
param (
[string]$timestamp = ((Get-Date) - (New-TimeSpan -Days 1)).ToString("yyyy-MM-dd")
)
Write-Host $timestamp
}
ā–¶ rdbl
2021-09-10
ā–¶ rdbl -timestamp 2021-09-01
2021-09-01

4. sources

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com