所以我和Powershell一直在争吵。我正在尝试制作像我放在这里的东西。我在脚本的开头声明了一个变量,然后我声明了2个函数。一个函数为变量设置一个值,另一个函数获取变量。
获取变量时,我什么也得不到 - 它是空的。
有没有人知道我做错了什么(我猜的是一些小而愚蠢的东西)
$ImUsedInMultplePlaces = ""
Function LetsChooseSomething
{
Write-Host "1: something"
Write-Host "2: Something else"
$answer = Read-Host "Pick One"
switch($answer)
{
"1" { $ImUsedInMultiplePlaces = "We chose something!"; Write-Host "I put it in there!" }
"2" { $ImUsedInMultiplePlaces = "We chose something else!"; Write-Host "I put it in there!" }
}
}
Function ShowMeMyChoice
{
Write-Host $ImUsedInMultiplePlaces
}
Write-Host "Welcome to this amazing script, im about to make you choose"
Write-Host ""
LetsChooseSomething
Write-Host ""
Write-Host "Great Choice!"
Write-Host ""
ShowMeMyChoice
答案 0 :(得分:1)
这是scope的问题。替换为这些,并试一试。
"1" { $global:ImUsedInMultiplePlaces = "We chose something!"; Write-Host "I put it in there!" }
"2" { $global:ImUsedInMultiplePlaces = "We chose something else!"; Write-Host "I put it in there!" }
答案 1 :(得分:1)
全局变量的使用使得软件更难以阅读和理解。由于程序中任何地方的任何代码都可以随时更改变量的值,因此理解变量的使用可能需要了解程序的大部分内容。全局变量使得将代码分离成可重用的库变得更加困难。它们可能导致命名问题,因为在一个文件中定义的全局变量可能与用于另一个文件中的全局变量的相同名称冲突(从而导致链接失败)。同名的局部变量可以保护全局变量不被访问,从而再次导致难以理解的代码。全局变量的设置可能会产生难以定位和预测的副作用。全局变量的使用使得为了单元测试而隔离代码单元变得更加困难;因此,它们可以直接导致降低代码质量。
我稍微重命名(并修改)了这些功能,旨在更加清晰。
第一个函数输出一个字符串:
function Select-Something
{
Write-Host "1: Something"
Write-Host "2: Something else"
$answer = Read-Host -Prompt "Pick One"
switch($answer)
{
"1" { [string]$output = "We chose something!" ; Write-Host "I put it in there!" }
"2" { [string]$output = "We chose something else!"; Write-Host "I put it in there!" }
}
return $output
}
通过向第二个函数添加([string])参数,它可以接受任何字符串:
function Show-Selection ([string]$Selection)
{
Write-Host $Selection
}
如您所见,它使代码更易于阅读:
Write-Host "Welcome to this amazing script, I'm about to make you choose."
Write-Host ""
$choice = Select-Something
Write-Host ""
Write-Host "Great Choice!"
Write-Host ""
Show-Selection $choice