Variable not updated when a function is called

I have this in my profile script.

$AddablePaths = @{ "python3"=";C:\Python32"; "python2"=";C:\Python27"; "D"=";C:\D\dmd2\windows\bin"; "gcc"=";C:\MinGW\bin"; "verge"=";C:\Users\Cold\Dev\Verge\tools"; "ruby"=";C:\Ruby192\bin"; "git"=";C:\Program Files\Git\cmd"; "cmake"=";C:\Program Files\CMake 2.8\bin"; "emacs"=";C:\Users\Cold\Dev\emacs\bin"; "notepad++"=";C:\Program Files\Notepad++"; "boost-build"=";C:\Users\Cold\Dev\C++\boost-build\bin"; "svn"=";C:\Program FIles\SlikSvn\bin"; "gtk2"=";C:\Program Files\GTK2-Runtime\bin"; "qt"=";C:\Qt\bin"; "komodo"=";C:\Program Files\ActiveState Komodo Edit 6\"; "hg"=";C:\Program Files\TortoiseHg\" } $AddedPaths = @() function AddPath($keys) { if ($keys.Count -eq 0) { return } foreach ($key in $keys) { if ($AddablePaths.Contains($key)) { if (!($AddedPaths -contains $key)) { $env:Path += $AddablePaths[$key] $AddedPaths += $key } } else { Write-Host "Invalid path option. Options are:" foreach ($key in $AddablePaths.keys) { Write " $key" } } } } 

The goal is to allow me to easily add only what I need to my path. For example, I can call AddPath("ruby","git","notepad++") to add these three things to my path. I want it not to add elements if I already added them, so I created an array of $AddedPaths to keep track of what has already been added. However, when the function is called, it is not updated, so duplicates can be added. What am I doing wrong?

+4
source share
3 answers

You will need to do this:

 $Global:AddedPathes += $key 

This should be the only place you need $Global: since it modifies it.

+5
source

If you make it a hash table instead of an array, you do not need to pop it up unless you reuse the same variable name in subsequent child areas.

+1
source

Since this function is in your profile, I think a global variable with areas is probably the best solution. However, I just wanted to tell you that there is another way.

In other scenarios (not profile functions, etc.) you can avoid global variables, but still there is a function that changes the variable, and the caller has access to this change. In this case, you can create a reference variable and pass it to your function (i.e., Pass by reference).

You would make an $AddedPaths type [ref] , and then pass it as a parameter to your function (now with a variable of reference type):

 function AddPath($keys, [ref]$ActivePaths) { if ($keys.Count -eq 0) { return } foreach ($key in $keys) { if ($AddablePaths.Contains($key)) { if (!($ActivePaths.Value -contains $key)) { $env:Path += $AddablePaths[$key] $ActivePaths.Value += $key } } else { Write-Host "Invalid path option. Options are:" foreach ($key in $AddablePaths.keys) { Write " $key" } } } } > [ref]$AddedPaths = @() > AddPath -keys ("ruby","git","notepad++") -ActivePaths $AddedPaths > $AddedPaths Value ----- {ruby, git, notepad++} 

To get more help on reference variables:

 > help about_ref 
+1
source

All Articles