1
votes

I am trying to create a windows form using PowerShell and then manipulate the data entered. The problem I am having is that I can get the code to work if I copy/paste it into a PowerShell window however I cannot get it to work if I save the exact same code to a PS1 file. I don't understand that.

If you try out the example in this article: http://technet.microsoft.com/en-us/library/ff730941.aspx it will work fine when you paste it into an open command prompt. If you try to save this code as a PS1 and run the PS1 in the PowerShell window I get nothing back when click OK on the dialog.

Can someone help me understand why it doesn't work as a PS1 file?

2
That's interesting. I tried it but my experience was a little different. The behavior was the same, either way. In both cases, it seems that $x was not assigned the string entered in the field. However, if I echo $objTextBox.Text then it does contain the text that I entered. For some reason, this assignment $x=$objTextBox.Text does not seem to be working (scoping problem?). However, for me, it was the same, regardless of whether I used the console for a script.David

2 Answers

3
votes

Variable assignment statement ($x=$objTextBox.Text) sets value within default scope, which is Local by default. As assignment statement is within {...} the variable value is not visible out of the assignment scope.

You can change the assignment statement $x=$objTextBox.Text with the:

$global:x=$objTextBox.Text

More info:

1
votes

As Matej stated this is a scope issue, and he provided an excellent solution to being able to manipulate variables from within a child scope.

I wanted to provide an alternative way to work around this issue. That is to declare variables at the beginning of the script with New-Variable and use the -Option AllScope argument. For example I will use the script that was referenced in the OP. Insert a line at line 3 to read:

New-Variable -Name x -Option AllScope

Now when you run the script it will output whatever you typed into the box because the variable $x is consistent across all scopes.