Hopefully you've arrived here before or just after exploring one of these pages:
Microsoft Invoke-Command
Ralph Kyttle's tidier, but slightly more confusing for the beginner, example
If so (or if you just want to read about this) you may be struggling with how to get variables into a session or remote command. The articles above have the information necessary but sometimes a fresh (and simpler) example will help out.
$Session = New-PSSession -ComputerName Test
$SomeWords = 'wow'
$SomeMoreWords = 'look at me'
$ArgumentsForTheSession = @($SomeWords,$SomeMoreWords)
Invoke-Command -Session $Session -ScriptBlock {Write-Host ($Args[0] + ' ' + $Args[1])} -ArgumentList $ArgumentsForTheSession
This is a simple remote command that will just return the words "wow look at me" from within the session/remote machine back to you.
Of course to prove you are on the remote machine you can always swap the last line out with:
Invoke-Command -Session $Session -ScriptBlock {Write-Host ($env:ComputerName + ': ' + $Args[0] + ' ' + $Args[1])} -ArgumentList $ArgumentsForTheSession
The results will be (if your DNS matches your hostnames): "Test: wow look at me"
Then you might want to run it against multiple machines to prove it can run against more than one so just add machines onto the first line:
$Session = New-PSSession -ComputerName Test,Test2,Test3
The results here will be:
"Test: wow look at me
Test2: wow look at me
Test3: wow look at me"
It's worthy of note that you can skip over the creation of a $Session variable and just run the Invoke-Command cmdlet with the -ComputerName parameter which, as far as this script is concerned, does exactly the same thing.
Hope this helps anyone wishing to work with variables in one or more remote sessions.
o7