【问题标题】:Powershell module and invoking filesPowershell 模块和调用文件
【发布时间】:2013-07-11 15:36:24
【问题描述】:

我有一个基于脚本的 powershell 模块 (.psm1),并将它导入到我的主脚本中。但是,此模块需要调用位于其同一目录内的批处理文件,但显然无法看到它。目前有问题的函数如下所示:

function MyFunction
{
    & .\myBatch.bat $param1 $param2
}

如何让函数看到批处理文件?

【问题讨论】:

    标签: shell powershell batch-file


    【解决方案1】:

    . 是当前工作目录,而不是模块所在的目录。后者可以通过MyInvocation variable 确定。将您的功能更改为:

    function MyFunction {
      $Invocation = (Get-Variable MyInvocation -Scope 1).Value
      $dir = Split-Path $Invocation.MyCommand.Path
      $cmd = Join-Path $dir "myBatch.bat"
      & $cmd $param1 $param2
    }
    

    【讨论】:

    • 为什么要在父范围内访问 MyInvocation?它不会在本地(脚本)范围内定义吗?我对此进行了测试,但它不起作用 - .Path 属性为空。我只是直接从脚本中访问 $MyInvocation 而没有范围修饰符。
    • 函数定义在一个模块中,他需要的是那个模块的路径,而不是导入模块的脚本的路径。
    • 我建议一个更紧凑的版本:& (Join-Path (Split-Path $script:MyInvocation.MyCommand.Path) 'myBatch.bat') $param1 $param2
    • @AdiInbar 我的答案有单独的陈述,因为这样更清楚每个步骤的作用。不过谢谢你的建议。
    【解决方案2】:

    试试这个:

    function MyFunction {
      & (Join-Path (Split-Path $MyInvocation.MyCommand.Path) 'myBatch.bat') $param1 $param2
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多