PowerShell示例交换中的变量范围问题

时间:2017-06-06 17:33:07

标签: function powershell variables scope swap

$global:value1
$global:value2
$global:value3

function initialize {
    $value1 = 100
    $value2 = 500
}

function subtract {
    $value3 = $value1 - $value2
    Write-Host $value3
}

function swap {
    Write-Host Before swap Value1: $value1 "& Value2: "$value2
    $value3 = $value1
    $value1 = $value2
    $value2 = $value3
    Write-Host After swap Value1: $value1 "& Value2: "$value2
}

function run-myscript {
    cls
    initialize
    subtract
    swap
    subtract
}

输出:

  

-400
  交换前Value1:100&价值2:500
  交换后Value1:500&价值2:100
  -400

请解释这个行为为什么我得到两个值为-400,我应该得到一次-400和第二次400

2 个答案:

答案 0 :(得分:0)

确定我每次都可以通过其范围进行调用,即全局

$global:value1
$global:value2
$global:value3
function initialize
{
$global:value1 = 100
$global:value2 = 500
}
function subtract
{
$global:value3 = $global:value1 - $global:value2
Write-Host $global:value3
}
function swap
{
Write-Host Before swap Value1: $value1 "& Value2: "$value2
$global:value3 = $global:value1
$global:value1 = $global:value2
$global:value2 = $global:value3
Write-Host After swap Value1: $value1 "& Value2: "$value2
}

function run-myscript
{
cls
initialize
subtract
swap
subtract
}

答案 1 :(得分:0)

您可能会读取在函数外部创建的全局值,但如果在函数内部设置值,则会在本地范围内新创建它们(除非您明确引用带有$Global:...的全局值)。 /> 因此,如果您在$value1 = $value2函数中设置了swap,则您有两个$value1值:一个本地$Local:Value1和一个全局:$Global:Value1
无论如何,一般来说,从函数中操纵全局变量不是一个好习惯。通常,您应该输入(管道或参数)和输出(管道)相关变量。 如果你这样做,你可能会看到光,并得出一个交换'功能'已存在:

$Value1, $Value2 = $Value2, $Value1