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"):
>>> 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}
> "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 = "$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
▶ rdbl -timestamp 2021-09-01

4. sources



Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at with a passion for cloud infrastructure/terraform/python/docs. More at