powershell - 对 Powershell 作用域处理 v2/v3 的未记录更改?

标签 powershell scope scriptblock

背景:我一直在编写一个 powershell 脚本,将文件从 Windows Server '08(使用 Powershell 2.x)上的 Sharpoint 2010 实例迁移到 Windows Server '12 上的 Sharepoint 2013 实例(使用 Powershell 3.x)。我可以正常工作,但我注意到处理范围的方式发生了变化。

问题:我有以下代码在两个 PSSession 上运行($param 是参数值的哈希表)

Invoke-Command -session $Session -argumentlist $params -scriptblock `
{
    Param ($in)
    $params = $in # store parameters in remote session

    # need to run with elevated privileges to access sharepoint farm
    # drops cli stdout support (no echo to screen...)
    [Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges(
    {
        # start getting the site and web objects
        $site = get-spsite($params["SiteURL"])
    })
}

我注意到在分配给 $site 的 PS 2.x 远程 session 中也分配给 Invoke-Command 范围内的相同变量,即任一范围获得通过或它们共享相同的范围。 但是 在分配给 $site 的 PS 3.x 远程 session 中 更改 Invoke-Command 中的值(真正的子范围)。

我的解决方案:我编写了一个函数来计算它调用的每个服务器上的正确范围,然后使用返回值作为 Get-VariableSet-Variable-Scope 选项。这解决了我的问题并允许分配和访问变量。

Function GetCorrectScope
{
    # scoping changed between version 2 and 3 of powershell
    # in version 3 we need to transfer variables between the
    # parent and local scope.
    if ($psversiontable.psversion.major -gt 2)
    {
        $ParentScope = 1 # up one level, powershell version >= 3
    }else
    {
        $ParentScope = 0 # current level, powershell version < 3
    }

    $ParentScope
}

问题:Microsoft 在哪里(如果有的话)对此进行了记录? (我在 TechNet 的 about_scope 中找不到它,它说它适用于 2.x 和 3.x,并且是我在其他问题中看到的标准引用)。

此外,是否有更好/正确的方法来做到这一点?

最佳答案

它记录在 WMF 3 发行说明的“对 WINDOWS POWERSHELL 语言的更改”部分。

Script blocks executed as delegates run in their own scope

Add-Type @"
public class Invoker
{
    public static void Invoke(System.Action<int> func)
    {
        func(1);
    }
}
"@
$a = 0
[Invoker]::Invoke({$a = 1})
$a

Returns 1 in Windows PowerShell 2.0 
Returns 0 in Windows PowerShell 3.0

关于powershell - 对 Powershell 作用域处理 v2/v3 的未记录更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18515186/

相关文章:

powershell - PowerShell 批量文件重命名中的奇怪行为

powershell - 为什么 PowerShell 的 `Get-ChildItem` 命令将参数 `d` 解析为 `Depth` ?

powershell - 通过批处理文件下载和安装 Python

c# - Powershell 为 Func<T> 而不是 Action<T> 创建脚本 block

function - 如何在脚本 block 外调用函数

powershell - Hudson不会使用Powershell插件运行任何Powershell脚本

python 3 : UnboundLocalError: local variable referenced before assignment

javascript - 从全局定义的函数访问函数作用域链

powershell - 将参数传递给 powershell 中的脚本 block

templates - Jinja 变量的范围可以超出内部 block 吗?