[SOLVED] Running IF Statements in a Function in Powershell

Issue

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.

Solution

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

replace $user with $Global:user

Answered By – swani14

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.