Assign Default Values to PowerShell Variables: Both Literals and Expressions.
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
- the example function opens The Most Dangerous Writing App with the duration of 1 minute
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