It’s amazing how often I’ll run across some seemingly mundane code and still get surprised by little code bits that get me saying “You can do that?!”.

I almost always end up going back to previous code projects and updating/changing the way I code on each of these little revelations. The nuggets of wisdom or “tidbits” that don’t seem to always show up in the PowerShell literature (or at least didn’t show up in mine). So here’s my attempt at sharing some of those.

Call local variables in Invoke-Command with $Using:variable

I used to pass parameters using the “argumentlist” switch in the invoke-command cmdlet whenever I needed local variables passed to a remote session. This works fine, but you have to remember which position in the $args array you’re using for each argument you add. After enough variables, you have to write yourself a little map to keep track of which variable you assigned to $args[14].

$Using: is just so much simpler and cleaner. You simply name variables in your local session. I saw this in someone else’s code a while back and it left me saying “You can do that?!”


$Process = Notepad
Invoke-Command -ComputerName TestServ1 -Scriptblock {Stop-Process -Name $Using:Process}

Call functions in a string using $(function)

For YEARS I did not know that you can insert functions into string statements. So I would end up doing funny things like:

$Date = Get-Date
$a = "1"
$b = "2"
$c = "3"
$numbers = $a + $b + $c
Write-Warning "This warning was triggered on $Date" by $numbers.

Apparently, if you use $(function) within a string statement, the function is called and the string output is concatenated. Mind was blown when I saw this one.


Write-Warning "This warning was triggered on the following date: $(Get-Date) by $(1..3)"

Access a property directly by wrapping a function in parentheses. (function).property

This one’s not as flashy as the last two to most PowerShell devs, but I’m still amazed by how little I see this trick used.

$Service = Get-Service -name WinDefend
Write-Output $Service.DisplayName

Which does work, but we can save some steps by just wrapping the function in parentheses and accessing the property directly.


(Get-Service -Name WinDefend).DisplayName

Disclaimer: All scripts and other powershell references on this blog are offered “as is” with no warranty. While these scripts are tested and working in my environment, it is recommended that you test these scripts in a test environment before using in your production environment.