简体   繁体   中英

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

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 ?

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM