背景: Windows Server '08 (Powershell 2.x を使用) の Sharpoint 2010 インスタンスから Windows Server '12 (Powershell 3.x を使用) の Sharepoint 2013 インスタンスにファイルを移行するための PowerShell スクリプトを作成しています。私はそれを機能させていますが、スコープの処理方法が変更されていることに気付きました。
問題: 両方の 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 リモート セッションで、 への割り当てが のスコープ内の同じ変数にも割り当てられていることに気付きましたInvoke-Command
。つまり、スコープが渡されるか、同じスコープを共有します。ただし、PS 3.x リモート セッションの割り当てでは(真の子スコープ)の値は変更され$site
ません。Invoke-Command
私の解決策:呼び出した各サーバーで正しいスコープを計算する関数を作成し、戻り値をGet-Variable
andSet-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 の両方に適用され、他の質問で見た標準的なリファレンスです)。
また、これを行うためのより良い/適切な方法はありますか?