Note that there are some explanatory texts on larger screens.

plurals
  1. POUndocumented changes to Powershell Scope handling v2/v3?
    text
    copied!<p><strong>Background</strong>: I've been writing a powershell script to migrate files from a Sharpoint 2010 instance on Windows Server '08 (with Powershell 2.x) to a Sharepoint 2013 instance on Windows Server '12 (with Powershell 3.x). I have that working but I noticed a change in how scope is handled.</p> <p><strong>Issue</strong>: I have the following code that gets run on both PSSessions (<code>$param</code> is a hashtable of parameter values)</p> <pre><code>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"]) }) } </code></pre> <p>I noticed that in the PS 2.x remote session that assigning to <code>$site</code> also assigned to the same variable in <code>Invoke-Command</code>'s scope, i.e. either scope gets passed or they share the same scope. <strong>BUT</strong> in the PS 3.x remote session assigning to <code>$site</code> does <em>not</em> change the value in <code>Invoke-Command</code> (true child scope).</p> <p><strong>My Solution</strong>: I wrote a function to compute the correct scope on each server which it calls and then uses the return value as an input to <code>Get-Variable</code> and <code>Set-Variable</code>'s <code>-Scope</code> option. This solved my problem and allows assignment and access of the variables.</p> <pre><code>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 &gt;= 3 }else { $ParentScope = 0 # current level, powershell version &lt; 3 } $ParentScope } </code></pre> <p><strong>The Question</strong>: Where, if anywhere, is this documented by Microsoft? (I couldn't find it in <a href="http://technet.microsoft.com/en-us/library/hh847849.aspx" rel="nofollow">about_scope</a> on TechNet, which says it applies to both 2.x and 3.x and is the standard reference I've seen in other questions).</p> <p>Also, is there a better/proper way to do this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload