-ScriptBlock Scope

by bobsdesk at 2012-09-14 16:46:28

I’ll start this new section with a basic question that I’ve found difficult to get information on. That is the scope of Invoke-Command using -ScriptBlock vs. -Command. I understand that I can pass -ArgumentList into -Scriptblock but I’ve seen some strange behavior where variables can work inside the block w/o being passed in the argument list. Also Variables created within the script block can persist. What exactly is the scope of -Scriptblock, is it the life of the Remote-PSSession? What is the primary difference (besides multiple commands) betwen -Command and -Scriptblock?
by DonJ at 2012-09-14 16:54:24
They’re actually the same parameter. -Command is technically an alias to -ScriptBlock. That’s why, if you look at the help for the command, you’ll never see -Command.

It’s actually kind of a legacy thing. It was -Command for real in some of the pre-release versions, and I think they just kept the alias in place to avoid confusing all of us who’d built up habits around that parameter name.

The script block you pass to -ScriptBlock is transmitted to the remote machines for execution. It runs in their global scope; if you’ve specified a -ComputerName, then that global scope is gone after the script block finishes executing. If you specified a -Session instead, then the global scope persists for the duration of the session. But it isn’t accurate to say that the script block’s scope is the life of the PSSession; technically, the script block runs "scopeless" inside the global scope of the remote runspace - as if you’d typed the command manually on the command-line there. So yes, any changes made by the script block will "permanently" modify that runspace, until it shuts down.

So you can always use variables inside the script block, and you can use any of the automatic variables that every PowerShell runspace is born with. -ArgumentList just populates a specific set of variables, so that you can pass "customized" information into the script block for each computer you’re targeting. What happens in the script block, however always happens on the remote machine, so nothing in there will affect the variables in the initiating machine’s runspace.