【问题标题】:Dot sourcing a PowerShell script not ending with .ps1点源不以 .ps1 结尾的 PowerShell 脚本
【发布时间】:2012-05-19 12:17:37
【问题描述】:

从一个 PowerShell 程序,我可以“点源”另一个 PowerShell 程序。即我可以执行它,就好像它写在第一个里面一样。
示例:

Write-Host 'before'
. MyOtherProgram.ps1
Write-Host 'after'

MyOtherProgram 在主程序中的“包含”中,就像它的内容已被复制/粘贴一样。

问题是:我只能点源一个以.ps1结尾的文件名
我不能用MyOtherProgram.libMyOtherProgram.whatever

任何人都有办法点源不以.ps1 结尾的 PowerShell 脚本?

【问题讨论】:

    标签: powershell dot-source


    【解决方案1】:

    另一种方法是使用Invoke-Expression

    $code = Get-Content ./MyOtherProgram.lib | Out-String
    Invoke-Expression $code
    

    【讨论】:

    • Invoke-Expression 与点源不同。您不能在函数库上调用表达式并能够调用这些函数。
    【解决方案2】:

    我不知道它是否被编译到 PowerShell 中,或者它是否可配置,但一种方法是让你的脚本暂时重命名它,导入它然后重命名它。

    Rename-Item C:\Path\MyScript.whatever C:\Path\MyScript.ps1
    . C:\Path\MyScript.ps1
    Rename-Item C:\Path\MyScript.ps1 C:\Path\MyScript.whatever
    

    【讨论】:

      猜你喜欢
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      相关资源
      最近更新 更多