我需要从函数设置一个全局变量,我不太清楚如何做到这一点.
# Set variables
$global:var1
$global:var2
$global:var3
function foo ($a, $b, $c)
{
# Add $a and $b and set the requested global variable to equal to it
$c = $a + $b
}
Run Code Online (Sandbox Code Playgroud)
调用函数:
foo 1 2 $global:var3
Run Code Online (Sandbox Code Playgroud)
最终结果:
$ global:var3设置为3
或者如果我这样调用函数:
foo 1 2 $global:var2
Run Code Online (Sandbox Code Playgroud)
最终结果:
$ global:var2设置为3
我希望这个例子有意义.传递给函数的第三个变量是要设置的变量的名称.
lat*_*kin 84
您可以使用Set-Variablecmdlet.传$global:var3发价值的$var3,这是不是你想要的.你想发送名字.
$global:var1 = $null
function foo ($a, $b, $varName)
{
Set-Variable -Name $varName -Value ($a + $b) -Scope Global
}
foo 1 2 var1
Run Code Online (Sandbox Code Playgroud)
不过,这不是很好的编程习惯.下面会更简单,以后不太可能引入错误:
$global:var1 = $null
function ComputeNewValue ($a, $b)
{
$a + $b
}
$global:var1 = ComputeNewValue 1 2
Run Code Online (Sandbox Code Playgroud)
小智 39
很简单:
$A="1"
function changeA2 () { $global:A="0"}
changeA2
$A
Run Code Online (Sandbox Code Playgroud)
zda*_*dan 17
您必须将参数作为引用类型传递.
#First create the variables (note you have to set them to something)
$global:var1 = $null
$global:var2 = $null
$global:var3 = $null
#The type of the reference argument should be of type [REF]
function foo ($a, $b, [REF]$c)
{
# add $a and $b and set the requested global variable to equal to it
# Note how you modify the value.
$c.Value = $a + $b
}
#You can then call it like this:
foo 1 2 [REF]$global:var3
Run Code Online (Sandbox Code Playgroud)
da_*_*ker 17
我在对自己的代码进行故障排除时遇到了这个问题
所以这不起作用......
$myLogText = ""
function AddLog ($Message)
{
$myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText
Run Code Online (Sandbox Code Playgroud)
这个APPEARS可以工作,但只能在PowerShell ISE中使用:
$myLogText = ""
function AddLog ($Message)
{
$global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText
Run Code Online (Sandbox Code Playgroud)
这实际上适用于ISE和命令行:
$global:myLogText = ""
function AddLog ($Message)
{
$global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $global:myLogText
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
279824 次 |
| 最近记录: |