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

3
背景:我一直在编写一个 Powershell 脚本,将文件从 Windows Server '08 上的 SharePoint 2010 实例(使用 Powershell 2.x)迁移到 Windows Server '12 上的 SharePoint 2013 实例(使用 Powershell 3.x)。我已经实现了这个功能,但我注意到作用域处理方式发生了变化。
问题:我有以下代码在两个 PSSessions 上运行($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"])
    })
}

我注意到在PS 2.x远程会话中,给$site赋值也会将其赋值给Invoke-Command的作用域中的同一变量,即它们要么共享同一个作用域,要么传递了同一个作用域。但是在PS 3.x远程会话中,给$site赋值不会改变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
}
问题: 微软在哪里有记录这个问题的解决方法?(我在TechNet上的about_scope中没有找到,该文档适用于2.x和3.x版本,并且是其他问题中标准的参考文献。)

此外,是否有更好/更合适的方法来解决这个问题?

1个回答

4

这在WMF 3版本发布说明的"WINDOWS POWERSHELL语言更改"章节中有记录。

作为委托执行的脚本块在其自己的范围内运行

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

谢谢。我甚至花了大约5分钟的时间才找到适当的发布说明文档(这个更改没有列在测试版说明中)。对于那些感兴趣的人,它们可以从Microsoft下载站点获取。 - CodePartizan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接