Graham Gold
Graham Gold

Reputation: 2485

Unable to set Description property of a variable using Set-Variable

I'm trying to write a function I can use to tag my variables as belonging to my script, so as I create them I can tag them for easier identification later (e.g. for debug).

The code below doesn't fail or display any errors, but also doesn't actually set the Description property:

Function Tagit([string[]]$params){foreach($param in $params){Set-Variable -name $param -Description "Script"}}
$filein="\\blah\blah"
[string[]]$RepsToRun = "IAM","OPS","ADMIN"
Tagit('filein','RepsToRun')

When run, I know it's properly processing the params variable because the parameter names passed in are written to the console.

However, if I check the variable, the description property is still not set e.g.

get-variable filein|select *


PSPath        : Microsoft.PowerShell.Core\Variable::filein
PSDrive       : Variable
PSProvider    : Microsoft.PowerShell.Core\Variable
PSIsContainer : False
Name          : filein
Description   : 
Value         : \\blah\blah
Visibility    : Public
Module        : 
ModuleName    : 
Options       : None
Attributes    : {}

Any ideas what I'm missing/doing wrong here?

EDIT Mike Shepard pointed out the obvious....scopes!

So the below code works:

Function Tagit([string[]]$params){$params|foreach{Set-Variable -name $_ -Description "Script" -scope 1}}
$filein="\\blah\blah"
[string[]]$RepsToRun = "IAM","OPS","ADMIN"
Tagit('filein','RepsToRun')
Get-Variable filein|select Name,Description,Value
Get-Variable RepsToRun|select Name,Description,Value

And returns:

filein
RepsToRun

Name      Description Value            
----      ----------- -----            
filein    Script      \\blah\blah      
RepsToRun Script      {IAM, OPS, ADMIN}

Upvotes: 0

Views: 182

Answers (1)

Mike Shepard
Mike Shepard

Reputation: 18176

Looks like a scoping problem. You are modifying a variable (copy of the outer variable) that is local to the function.

As you found, you can specify scope with Set-Variable using the -scope parameter.

Upvotes: 2

Related Questions