How to enumerate all locally declared script variables?

322 Views Asked by At

Is there a way to get only the locally declared variables in a powershell script?

In this snippit, I would want it to return only myVar1, myVar2, anotherVar:

$myVar1 = "myVar1"
$myVar2 = "myVar2"
$anotherVar = "anotherVar"
Get-Variable -Scope Script 

But it instead returns a ton of other local script variables.

The problem I'm trying to solve, and maybe you can suggest another way, is that I have many Powershell scripts that have a bunch of misc variable constants declared at the top.

I want to export them all to disk (xml) for import later.

So to call Get-Variable bla* | Export-Clixml vars.xml, I need to know all of the variable names.

So is there a way I can like do

$allVars = {
    $myVar1 = "alex"
    $myVar2 = "iscool"
    $anotherVar = "thisisanotherVar"
}
Get-Variable allVars | Export-Clixml "C:\TEMP\AllVars.xml"

And then later Import-Clixml .\AllVars.xml | %{ Set-Variable $_.Name $_.Value } ?

So that the rest of the script could still use $myVar1 etc without major changes to what is already written?

1

There are 1 best solutions below

9
Matt On BEST ANSWER

The issue is there are more variables that are accessible in that scope beyond the ones you already declared. One thing you could do is get the list of variables before you declare yours. Get another copy of all the variables and compare the list to just get yours.

$before = Get-Variable -Scope Local
$r = "Stuff"
$after =  Get-Variable -Scope Local

# Get the differences
Compare-Object -Reference $current -Difference $more -Property Name -PassThru

The above should spit out names and simple values for your variables. If need be you should be able to easily send that down the pipe to Export-CliXML. If your variables are complicated you might need to change the -depth for more complicated objects.

Caveat: If you are changing some default variable values the above code currently would omit them since it is just looking for new names.

Also not sure if you can import them exactly in the same means as they were exported. This is largely dependent on your data types. For simple variables this would be just fine

I need to know all of the variable names.

The only other way that I am aware of (I never really considered this) would be to change all of the variable to have a prefix like my_ so then you could just have one line for export.

Get-Variable my_* | Export-Clixml vars.xml