How to Use Subexpressions Within Strings in Powershell

On the power of $( )

Pavol Kutaj
2 min readFeb 21, 2022

The aim of this page📝 is to share the use and weirdness of PowerShell’s Subexpression operator $( ) notation. Weird, because if you are combining the use of a subexpression operator with a variable name — it's "two dollars" $($. In bash, there indeed is command substitution and this is somewhat similar.

echo "the length is $($list.length)"
echo "today is $(Get-Date)"

EXAMPLE_1

  • this is used for a logger to stdout when printing a many jobs at once, I want to see the progres (e.g job# 3/15)
$i = 1
foreach ($jobId in $jobIds) {
if($jobIds.length -gt 1) {
Write-Host "-- Dwarf Counts: Job #${i}/$($jobIds.length) --" -backgroundcolor DarkYellow-foregroundcolor Magenta
$i++
Pause}
}

EXAMPLE_2

  • I copy the $url and $title to the clipboard of a page with the help of a Chrome expression
  • Then I call this tiny function which
  • creates a bookmarked file where I can come later to add notes if needed
  • importantly, it automatically populates playlist.md which you can see at read_list | âś’ Pavol Kutaj âś’
  • the significant line is "* $(read-host 'notes')" >> $playlist_path because it concatenates * with the input from terminal and appends to the path without having to need the terminal
function bookmark($url,$title) {
$title = $title -replace "\|.*"
$playlist_path = "C:\Users\Admin\Documents\workspace\work.log\pkutaj\playlist.md"
echo "`n#### $title" >> $playlist_path
echo "* $url" >> $playlist_path
"* $(read-host 'notes')" >> $playlist_path
New-Kba k -name $title -url $url -cat "bookmarks" -extract $title
}

LINKS

--

--

No responses yet