0

I'm a total Powershell newbie and I'm having difficulty with a script I'm trying to come up with.

The script creates a form to map network drives, and as some of those drives are on a different domain it gives the user the option to enter a username themselves $txtUsername.Text or use the currently logged in user name $LoggedInUser.

When the user clicks the OK button on the form, the function btnOK_Click is called and I want it to essentially to run this statement: If ($txtUsername.Text -eq "") {$User = $LoggedInUser } Else {$User = $txtUsername.Text}

If I run that statement manually, it works as expected - $User is set to the value the user enters, or if they don't enter a value it uses the currently logged in username. But I can't figure out how to make it work within a function. If I try it like this:

function btnOK_Click {If ($txtUsername.Text -eq "") {$User = $LoggedInUser } Else {$User = $txtUsername.Text}}

Nothing happens - $User isn't defined - though there are no errors.

Can anyone point me in the right direction? If it helps I can post the whole code I have, but as it's 250+ lines, I thought it best to just post the part I'm having trouble with.

  • 3
    You're defining and assigning `$user` inside a function, the variable will __only live inside that scope__. – Santiago Squarzon Feb 11 '22 at 19:42
  • 2
    For an overview of how scopes work in PowerShell, see the bottom section of [this answer](https://stackoverflow.com/a/36347515/45375). – mklement0 Feb 11 '22 at 19:54
  • 1
    Ah, that's very helpful - thank you both. I'll read through that answer tomorrow (it's 10pm here in the UK - time for a few cold ones!) But I've skimmed through it, and it does indeed seem to answer my question. – Wiltshire77 Feb 11 '22 at 21:59

1 Answers1

0

make your $user variable global & therefore accessible outside of your function

replace $user with $Global:user

swani14
  • 34
  • 3