背景:我一直在编写一个 powershell 脚本,用于将文件从 Windows Server '08(使用 Powershell 2.x)上的 Sharpoint 2010 实例迁移到 Windows Server '12(使用 Powershell 3.x)上的 Sharepoint 2013 实例。我已经做到了这一点,但我注意到范围的处理方式发生了变化。
Issue:我有以下代码可以在两个 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"])
})
}
我注意到在 PS 2.x 远程会话中分配给$site
也分配给相同的变量Invoke-Command
的范围,即要么范围被传递,要么它们共享相同的范围。BUT在 PS 3.x 远程会话中分配给$site
does not改变其中的值Invoke-Command
(真正的子范围)。
我的解决方案:我编写了一个函数来计算它调用的每个服务器上的正确范围,然后使用返回值作为输入Get-Variable
and Set-Variable
's -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 在哪里(如果有的话)对此进行了记录? (我在关于范围 http://technet.microsoft.com/en-us/library/hh847849.aspx在 TechNet 上,它说它适用于 2.x 和 3.x,并且是我在其他问题中看到的标准参考)。
另外,有没有更好/正确的方法来做到这一点?