简体   繁体   English

在 Powershell 中运行 886982359588 中的 IF 语句

[英]Running IF Statements in a Function in Powershell

I'm a total Powershell newbie and I'm having difficulty with a script I'm trying to come up with.我总共是 Powershell 新手,我在尝试编写脚本时遇到困难。

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 .该脚本创建一个 map.network 驱动器的表单,并且由于其中一些驱动器位于不同的域中,它使用户可以选择自己输入用户名$txtUsername.Text或使用当前登录的用户名$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}当用户单击表单上的“确定”按钮时,将调用 function btnOK_Click ,我希望它基本上运行此语句: 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.如果我手动运行该语句,它会按预期工作 - $User设置为用户输入的值,或者如果他们没有输入值,它会使用当前登录的用户名。 But I can't figure out how to make it work within a function. If I try it like this:但我不知道如何让它在 function 内工作。如果我这样尝试:

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

Nothing happens - $User isn't defined - though there are no errors.没有任何反应 - $User未定义 - 尽管没有错误。

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.如果有帮助,我可以发布我的全部代码,但由于它有 250 多行,我认为最好只发布我遇到问题的部分。

make your $user variable global & therefore accessible outside of your function使您的 $user 变量成为全局变量,因此可以在 function 之外访问

replace $user with $Global:user将 $user 替换为 $Global:user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM