Using Subcommands in PowerShell for Simple Inline Queries

Posted by:

|

On:

|

Subcommands in PowerShell are essentially an expression or query used in line to avoid having to define a new variable or break up a string.

For instance, instead of:

PowerShell
$currentMonth = Get-Date -Format MMyy
Write-Output("Today's date is $CurrentDate.")

We can do this:

PowerShell
Write-Output("Today's date is $(Get-Date -Format MMyy).")

Alternatively, we can also perform operations on variables without changing the variable data.

PowerShell
$chosenNumber = Read-Host("Choose a number 1-10")
if (($chosenNumber -gt 0) -and $chosenNumber -lt 11) {
    Write-Output("Your number is $(20 - $chosenNumber) away from 20.")
    }

This falls more in line with “command-line scripting” in PowerShell, as it makes it easier to bang out things in the terminal. Be careful you don’t use this so frequently that it hurts the readability of your scripts for future use in functions or modules. Sometimes variable assignment is better.