【问题标题】:Powershell line of code does not run when called through function but will run directly. What could be possible causes?Powershell 代码行在通过函数调用时不运行,而是直接运行。可能的原因是什么?
【发布时间】:2012-02-24 21:54:17
【问题描述】:

我有一个包含以下代码的 powershell 脚本...

$appdir = Split-Path -Path $MyInvocation.MyCommand.Path
$xfrdir = $appdir + "\xfr\"
$cfgFile = "ofx_config.cfg"
$cfgPath = $appdir + "\" + $cfgFile
$configData = New-Object System.Collections.ArrayList
#  --- some other code here...
function Load-Config () 
{
    if (test-path ($cfgPath))
    {
        $configData = Import-Clixml -path "$cfgPath"
    } 
}
#  ---some other code here
load-config

当我在 ps ISE 中运行此脚本时,load-config 会运行,因为它位于脚本的末尾(我使用断点验证了这一点),但 $configData 变量仍然为空。

但是,如果我立即将 $configData = Import-Clixml -path "$cfgPath" 行复制并传递到 powershell 命令行并运行它,则 $configData 将加载数据。有没有人有任何想法可能会发生什么?

编辑
我认为您所说的是由于范围规则,$configData = Import-Clixml -path "$cfgPath" 中的 $configData 被视为一个完整的单独变量(并且是函数的本地变量)。我认为它更像是一个 c# 类,因此会分配给同名的脚本级变量。

我喜欢 powershell,但动态类型确实让事情变得更棘手。

编辑 2
两个答案都很有见地。在这种情况下,我通常会向声誉最低的人提供答案。无论如何,我确实做了安迪的第二个例子。

赛斯

【问题讨论】:

    标签: powershell powershell-ise


    【解决方案1】:

    您创建了名称为 $configData 的新变量。您有多种选择(取决于您的环境/脚本/...)

    最明显的是 - 只需返回值并将其分配给配置数据

    function Load-Config () 
    {
        if (test-path ($cfgPath))
        {
            Import-Clixml -path "$cfgPath"
        } 
    }
    $configData = load-Config
    

    您也可以像这样使用对象及其属性:

    $configData = @{Data = $null}
    function Load-Config () 
    {
        if (test-path ($cfgPath))
        {
            $configData.Data = Import-Clixml -path "$cfgPath"
        } 
    }
    

    或者可以使用script:范围:

    function Load-Config () 
    {
        if (test-path ($cfgPath))
        {
            $script:configData = Import-Clixml -path "$cfgPath"
        } 
    }
    

    【讨论】:

      【解决方案2】:

      变量$configData 存在范围问题。当您在函数中设置它的值时,它在外部不可用。您可以使用范围修饰符来修复它或返回值。

      查看get-help about_scopes 或点击here

      范围修饰符:

      $cfgPath = 'C:\Test.xml'
      $script:configData = New-Object System.Collections.ArrayList
      
      function Load-Config () 
      {
          if (test-path ($cfgPath))
          {
              $script:configData = Import-Clixml -path "$cfgPath"
          }
      }
      load-config
      $configData
      

      注意 - 您的 ArrayList 会被 Import-Clixml 覆盖,并且在返回时是不同的类型。

      返回新值:

      $cfgPath = 'C:\Test.xml'
      function Load-Config () 
      {
          if (test-path ($cfgPath))
          {
              $data = Import-Clixml -path "$cfgPath"
              return $data
          }
      }
      $configData = load-config
      

      【讨论】:

        猜你喜欢
        • 2011-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-05
        • 2012-08-30
        • 2015-03-24
        • 1970-01-01
        相关资源
        最近更新 更多