相关疑难解决方法(0)

将参数传递给PowerShell中的scriptblock

我猜你不能这样做:

  $servicePath = $args[0]

  if(Test-Path -path $servicePath) <-- does not throw in here

  $block = {

        write-host $servicePath -foreground "magenta"

        if((Test-Path -path $servicePath)) { <-- throws here.

              dowork 
        }
  }
Run Code Online (Sandbox Code Playgroud)

那么如何将我的变量传递给scriptblock $ block?

powershell scriptblock

40
推荐指数
4
解决办法
7万
查看次数

什么是PowerShell ScriptBlock

PowerShell ScriptBlock不是词法闭包,因为它不会关闭其声明环境中引用的变量.相反,似乎利用动态范围和自由变量,这些变量在运行时绑定在lambda表达式中.

function Get-Block {
  $b = "PowerShell"
  $value = {"Hello $b"}
  return $value
}
$block = Get-Block
& $block
# Hello
# PowerShell is not written as it is not defined in the scope
# in which the block was executed.


function foo {
  $value = 5
  function bar {
    return $value
  }
  return bar
}
foo
# 5
# 5 is written $value existed during the evaluation of the bar function
# it is my understanding …
Run Code Online (Sandbox Code Playgroud)

powershell lambda closures scope function

11
推荐指数
2
解决办法
1万
查看次数

标签 统计

powershell ×2

closures ×1

function ×1

lambda ×1

scope ×1

scriptblock ×1