什么是PowerShell ScriptBlock [英] What exactly is a PowerShell ScriptBlock

查看:703
本文介绍了什么是PowerShell ScriptBlock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A PowerShell ScriptBlock is not a lexical closure as it does not close over the variables referenced in its declaring environment. Instead it seems to leverage dynamic scope and free variables which are bound at run time in a lambda expression.

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 that a function is a named scriptblock
#  which is also registered to function:



在ScriptBlock调用GetNewClosure()返回一个新的ScriptBlock其关闭所引用的变量。

Calling GetNewClosure() on a ScriptBlock returns a new ScriptBlock which closes over the variables referenced. But this is very limited in scope and ability.

ScriptBlock的分类是什么?

What is a ScriptBlock's classification?

推荐答案

文档,脚本块是一个预编译脚本文本块。所以默认情况下,你只是一个预解析的脚本块,没有更多,没有更少。执行它创建一个子范围,但除此之外,就像你在内嵌代码。因此,最合适的术语只是只读源代码。

Per the docs, a scriptblock is a "precompiled block of script text." So by default you just a pre-parsed block of script, no more, no less. Executing it creates a child scope, but beyond that it's as if you pasted the code inline. So the most appropriate term would simply be "readonly source code."

在动态生成的模块上调用 GetNewClosure 它在调用 GetNewClosure 时基本上包含调用者作用域中所有变量的快照。它不是一个真正的闭包,只是变量的快照副本。脚本块本身仍然只是源代码,并且变量绑定不会发生,直到它被调用。您可以随意添加/删除/编辑所附模块中的变量。

Calling GetNewClosure bolts on a dynamically generated Module which basically carries a snapshot of all the variables in the caller's scope at the time of calling GetNewClosure. It is not a real closure, simply a snapshot copy of variables. The scriptblock itself is still just source code, and variable binding does not occur until it is invoked. You can add/remove/edit variables in the attached Module as you wish.

function GetSB
{
   $funcVar = 'initial copy'

   {"FuncVar is $funcVar"}.GetNewClosure()

   $funcVar = 'updated value'  # no effect, snapshot is taken when GetNewClosure is called
}

$sb = GetSB

& $sb  # FuncVar is initial copy

$funcVar = 'outside'
& $sb  # FuncVar is initial copy

$sb.Module.SessionState.PSVariable.Remove('funcVar')
& $sb  # FuncVar is outside

这篇关于什么是PowerShell ScriptBlock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆