Friday, 23 August 2013

Powershell does not resolve dynamic variables

I have been working diligently on a script to create Sharepoint groups in Powershell. It sounds easy enough until you have to create iterated allocations. For example, a group needs to be allocated permissions to multiple lists. This is where the fun starts:

My code was as follows:
For($i=0; $i -lt $scopes.Length; $i++) {
if (($scopes[$i] -ne $null) -and ($scopes[$i] -ne ""))
$list = $web.Lists["$scopes[$i]"]

if ($list.HasUniqueRoleAssignments -eq $false)



It compiles and runs, but I was getting a lot of error messages about unassigned variables in the RoleAssignment addition. Very frustrating.

The problem was traced to $list = $web.Lists["$scopes[$i]"]
Powershell will not resolve the 'inner" variable, which cause the lookup to return a null value.

The solution was simple. Put the value in a variable and use the variable.
$name = $scopes[$i]
$list = $web.Lists["$name"]

I wish I had thought of that 2 hours ago.

No comments:

Post a comment