$using

A comment on yesterday’s post about passing parameters into a script block asked why I hadn’t mention $using

$using allows you to access a local variable in a scriptblock

BUT you need to be careful

PS> $proc = "power*"
Invoke-Command -ScriptBlock {
    Get-Process -Name $using:proc
 } 

 A Using variable cannot be retrieved. A Using variable can be used only with 
 Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is 
 used with Invoke-Command, the Using variable is valid only if the script block 
 is invoked on a remote computer.
 At line:4 char:4
 +    Get-Process -Name $using:proc
 +    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
     + FullyQualifiedErrorId : UsingWithoutInvokeCommand

What about the call operator?

PS> $proc = "power*"
& {
    Get-Process -Name $using:proc
 } 

 A Using variable cannot be retrieved. A Using variable can be used only with 
 Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is 
 used with Invoke-Command, the Using variable is valid only if the script block 
 is invoked on a remote computer.
 At line:4 char:4

 +    Get-Process -Name $using:proc
 +    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
     + FullyQualifiedErrorId : UsingWithoutInvokeCommand

And in a job?

PS> $proc = "power*"

Start-Job -ScriptBlock {
    Get-Process -Name $using:proc
 }

Id     Name            PSJobTypeName   State         HasMoreData     Location  
 --     ----            -------------   -----         -----------     --------  
 3      Job3            BackgroundJob   Running       True            localhost

PS> Receive-Job -Id 3

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName          
 -------  ------    -----      -----     ------     --  -- -----------          
     510      26    42192      58004       0.55   9172   9 powershell           
     634      30    73112      90028       1.53  14680   9 powershell           
     955      68   161040     159956      12.23   4012   9 powershell_ise

You can’t use $using with the call operator and if you use it with Invoke-Command you have to be accessing a remote computer.

$using with InlineScript is for accessing variables defined elsewhere in the workflow

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s