Using hash table expressions in Powershell jobs

I discovered a bit of strangeness when using hash table expressions in remote or background job script blocks. It appears that if you use a hash table expression within the script block, it creates a new scope.

Within the job’s main script block, $args[0] is visible, but within the hash table expression it is not:

$f = gci “c:\windows\win.ini”

start-job -Name testjob `
-scriptblock {
“`nFile Length is $($args[0].length)”
$args[0] | select name,@{name=”File Length”;expression={$args[0].length}}} -argumentlist $f
start-sleep 1
receive-job testjob

File Length is 478

Name : win.ini
File Length :
RunspaceId : 2d83ed6f-f043-46b2-9a43-118ff5b3eae7

Explicilty scoping $arg[0] to the Script scope makes it visible within the hash table expression:

start-job -Name testjob2 `
-scriptblock {
“`nFile Length is $($args[0].length)”
$args[0] | select name,@{name=”File Length”;expression={$script:args[0].length}}} -argumentlist $f
start-sleep 1
receive-job testjob2

File Length is 478

Name : win.ini
File Length : 478
RunspaceId : 007dac70-a038-417d-a35a-c197118da91d

Update – after thinking about it a little more it seems that using a hash table expression probably always creates a new scope.  What’s not immediatley apparent is that the creation of a new scope implicitly initilizes an new $args array for that scope.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s