背景:我一直在編寫一個powershell腳本,將文件從Windows Server '08上的Sharpoint 2010實例(包含Powershell 2.x)遷移到Windows Server '12上的Sharepoint 2013實例(包含Powershell 3.x )。我有這個工作,但我注意到如何處理範圍的變化。Powershell Scope處理v2/v3的未更改記錄?
問題:我有大幹快上兩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
的範圍中的相同變量,即,範圍被傳遞或者它們共享相同的範圍。 但是在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,並且是我在其他問題中看到的標準參考)。
另外,有沒有更好/正確的方法來做到這一點?
謝謝。它甚至花了我大約5分鐘的時間來找到正確的發行說明文件(這個改變沒有在測試版說明中列出)。對於那些感興趣,他們可以從[微軟下載網站在這裏](http://download.microsoft.com/download/E/7/6/E76850B8-DA6E-4FF5-8CCE-A24FC513FD16/WMF%203%20Release% 20Notes.docx) – CodePartizan