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"
}
}
}
}
It's purpose is to allow me to be able to easily add to my path only the things that I need. For example, I can call AddPath("ruby","git","notepad++")
to add those three things to my path. I want that it doesn't add items if I already added them, so I created the $AddedPaths
array to keep track of what's been added already. However, it doesn't update when I call the function, so duplicates can still be added. What am I doing wrong?
Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).
If you assign a value to a variable that you have not declared with var , JavaScript implicitly declares that variable for you. Note, however, that implicitly declared variables are always created as global variables, even if they are used within the body of a function.
Automatically Global If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare a global variable carName , even if the value is assigned inside a function.
Updating Variables We can update our variables in shorter ways by using the += , *= , -= or /= operators. This way, we don't have to repeat the variable name when we assign them to something. Then we increase the value of i by 2. If we increment or decrement only by 1, then we can use ++ or -- respectively.
You'll need to do this:
$Global:AddedPathes += $key
That should be the only place you need $Global:
since it modifies it.
If you make it a hash table instead of an array, you don't have to scope it at all unless you re-use the same variable name in subsequent child scopes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With