0

I have created a simple GUI to enter some values that are stored in a .txt file as soon as the User clicks OK. For verification I'm displaying the data of the just created file with its input in a popup window.

As I want to use the data of the config file in several other .ps1 files that I'm using for a project, I started to move things into a globals.ps1 file. Everything works great, with the exception that I can no longer display the hashtable.

Here's what I have in my globals.ps1 :

# Wshell popup
$wshell = New-Object -ComObject Wscript.SHell

# read config
function readcfg
{
    Get-Content -Path $cfg | foreach-object -begin { $conf = @{ } } -process {`
        $key = [regex]::split($_, ':');
        if (($key[0].CompareTo("") -ne 0) -and ($key[0].StartsWith("[") -ne $True))`
        { $conf.Add($key[0], $key[1]) }
    }
}

And this is the part in my settings GUI which is executed if the OK button is pressed:

$cfgData = "
[Account]
Screds:" + $Admaccount.text + "
Spw:" + $PW + "

[Domainconfig]
Sdomain:" + $domain.text + "
SSearchBase:" + $searchBase.text + "
SdeactivatedUsers_OU:" + $deactivatedUsersOU.text + ""
    Out-File -filepath $cfg -inputobject $cfgData -Force
    Start-Sleep -s 1
    $wshell.Popup("Settings saved:`nAccount: " + $conf.Screds + "`nDomain: " + $conf.Sdomain + "`nSearchBase: " + $conf.SSearchBase + "`ndeactivatedUsersOU " + $conf.SdeactivatedUsers_OU + "", 0, "Yarr...!", 0x0) 

If I move the get-Content out of the readcfg function, I can display the values again. But that's of course not the solution, as it will display the old data if the settings are changed and the popup comes up again.

What am I missing here?

2
  • $cfg is never defined it seems. Your problem is certainly a scope issue try to use the global prefix when you define it : $global:cfg="c:\...." , use the same prefix inside your function Commented Feb 5, 2015 at 12:35
  • yes thank you. that was the issue. Commented Feb 5, 2015 at 15:15

1 Answer 1

1

As stated by Kayasax in the comments, it was simply a "out of scope" issue.

after declaring the function and hashtable as global, it all works perfectly again.

# read config
function global:readcfg
{
    Get-Content -Path $cfg | foreach-object -begin { $global:conf = @{ } } -process {`
        $key = [regex]::split($_, ':');
        if (($key[0].CompareTo("") -ne 0) -and ($key[0].StartsWith("[") -ne $True))`
        { $global:conf.Add($key[0], $key[1]) }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.