Powershell $using variable not working with Invoke-Command in scriptblock

1k Views Asked by At

I'm trying to use $using:x inside an Invoke-Command itself called by Start-Job, but I can't figure it out:

$x = "yeah"

$sb = {
  param($n)
  '{0}: {1}' -f $n, $using:x

  # Does not work
  Invoke-Command -ComputerName PC -ScriptBlock { 'invoke: {0}' -f $using:x }

  # Does not work either
  # $y = 'foo'
  # Invoke-Command -ComputerName PC  -ScriptBlock { 'invoke2: {0}' -f $using:y }

  # WORKAROUND 
  # Invoke-Command -ComputerName PC -ScriptBlock { param($y) 'invoke3: {0}' -f $y } -ArgumentList $using:x
}

Start-Job -ScriptBlock $sb -ArgumentList 'job' | Receive-Job -Wait -AutoRemoveJob

This outputs:

Start-Job : The value of the using variable '$using:x' cannot be retrieved because it has not been set in the local session.

I know I can simply pass the value with -ArgumentList as in my workaround, but I'm curious what would be needed for the $using:x to work. Maybe retrieve the current session and pass it to Invoke-Command ?

1

There are 1 best solutions below

0
Narayana Lvsl On

Please follow the below example syntax to achieve your goal. Because, from your code, I see Variable X is not declared

$Log = "PowerShellCore/Operational"

Invoke-Command -ComputerName Server01 -ScriptBlock {Get-WinEvent -LogName $Using:Log -MaxEvents 10}