背景:我一直在编写一个 Powershell 脚本,将文件从 Windows Server '08 上的 SharePoint 2010 实例(使用 Powershell 2.x)迁移到 Windows Server '12 上的 SharePoint 2013 实例(使用 Powershell 3.x)。我已经实现了这个功能,但我注意到作用域处理方式发生了变化。
问题:我有以下代码在两个 PSSessions 上运行($param 是参数值的哈希表)。
我注意到在PS 2.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-Variable
和Set-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版本,并且是其他问题中标准的参考文献。)
此外,是否有更好/更合适的方法来解决这个问题?