【问题标题】:Odd Powershell Variable Behavior奇怪的 Powershell 变量行为
【发布时间】:2014-06-05 14:27:31
【问题描述】:

下面的脚本演示了 powershell 中令人困惑的意外行为。这个问题很可能是我做错了,但我无法弄清楚。该脚本查看特定日期的特定时间,并根据一组参数采取各种操作。我有一个布尔值,它在包含的循环的迭代中交替。或者至少它应该,这就是问题所在。这是一个示例脚本,它演示了我如何使用变量并产生奇怪的行为:

$DisabledRequests = $false
$Time = Get-Date -UFormat %R
$Day = Get-Date -UFormat %u

function checktime() {


if($Time -ge "07:00" -and $Time -le "19:00" -and $Day -le "5"){

    if($DisabledRequests -eq $false){
        Write-Host "Time is $time, Day is $day.  Inside disabledrequests -eq false statement."
        $DisabledRequests = $true #Sets variable to true
        $DisabledRequests -eq $true #Prints true on the console because the statement is true
    }else{


    }

}else{

    Write-Host "Outside limited time parameters."
    if($DisabledRequests -eq $true){
            Write-Host "Changing disabled requests var to false."
            $DisabledRequests = $false
    }
}

}


for($i=0; $i -le 10; $i++){
checktime
}

预期的行为是脚本应该循环通过条件(目前相对于时间的条件应该导致$true),然后另一个条件检查$DisabledRequests 变量的状态。因为变量最初是$false,所以条件在第一次迭代时正确运行。该条件的部分操作是将变量$DisabledRequests 设置为$true,它确实如此。至少,关于$DisabledRequests -eq $true 的部分会在控制台上打印“True”。

问题是,如果$DisabledRequests 变量现在为真,为什么条件($DisabledRequests -eq $false) 仍被评估为真?

编辑:

我还想补充一点,我已尝试使用 Clear-Variable 清除变量,然后将 Set-Variable 设置为 true 重新创建它,但这也无法按预期工作。

【问题讨论】:

    标签: variables loops conditional-statements powershell-ise


    【解决方案1】:

    您的问题与作用域有关 - 在函数内部创建的变量(使用显式作用域限定符分配)在函数退出后不再存在。

    如果,当您分配给变量时,您使用:

    $script:DisabledRequest = $true
    

    然后你会看到你所期望的。有关范围的更多信息,您可以阅读内置帮助“about_Scopes”和“about_Variables”中的主题,可在此处在线获取:http://technet.microsoft.com/en-us/library/hh847849.aspxhttp://technet.microsoft.com/en-us/library/hh847734.aspx

    【讨论】:

      猜你喜欢
      • 2014-09-24
      • 2011-12-05
      • 2021-10-27
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多