powershell - 点源脚本而不执行它

标签 powershell

在 Powershell 中是否可以在不执行的情况下点源或重用脚本函数?我试图重用脚本的功能,而不执行脚本本身。我可以将函数分解为仅函数文件,但我试图避免这样做。

点源文件示例:

function doA
{
    Write-Host "DoAMethod"
}

Write-Host "reuseme.ps1 main."

消费文件示例:
. ".\reuseme.ps1"

Write-Host "consume.ps1 main."
doA

执行结果:
reuseme.ps1 main.
consume.ps1 main.
DoAMethod

期望的结果:
consume.ps1 main.
DoAMethod

最佳答案

您必须执行函数定义才能使它们可用。没有其他办法了。

您可以尝试将 PowerShell 解析器扔到文件中,只执行函数定义而不执行其他任何操作,但我想更简单的方法是将可重用部分构建为模块或简单地构建为除了声明函数之外不做任何事情的脚本。

作为记录,一个粗略的测试脚本可以做到这一点:

$file = 'foo.ps1'

$tokens = @()
$errors = @()
$result = [System.Management.Automation.Language.Parser]::ParseFile($file, [ref]$tokens, [ref]$errors)

$tokens | %{$s=''; $braces = 0}{
    if ($_.TokenFlags -eq 'Keyword' -and $_.Kind -eq 'Function') {
        $inFunction = $true
    }
    if ($inFunction) { $s += $_.Text + ' ' }
    if ($_.TokenFlags -eq 'ParseModeInvariant' -and $_.Kind -eq 'LCurly') {
        $braces++
    }
    if ($_.TokenFlags -eq 'ParseModeInvariant' -and $_.Kind -eq 'RCurly') {
        $braces--
        if ($braces -eq 0) {
            $inFunction = $false;
        }
    }
    if (!$inFunction -and $s -ne '') {
        $s
        $s = ''
    }
} | iex

如果脚本中声明的函数引用脚本参数(因为不包括脚本的参数 block ),您将遇到问题。可能还有很多我现在想不到的其他问题。我最好的建议仍然是区分可重用的库脚本和打算调用的脚本。

关于powershell - 点源脚本而不执行它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17991679/

相关文章:

powershell - 为什么是Get-DnsClientServerAddress |选择AddressFamily输出不是IPv4和IPv6

azure - 如何使用 Powershell 从订阅获取 Cosmos DB 的数据大小

powershell - Windows 中的 Git Shell : patch's default character encoding is UCS-2 Little Endian - how to change this to ANSI or UTF-8 without BOM?

powershell - 如何通过 PowerShell 或模板将 Azure 混合连接链接到 Azure Web 应用?

powershell - 显示文件名

java - 访问 PowerShell 对象中的文本。为什么它似乎不存储在数组中?

powershell - 由于组策略,Powershell脚本 'Basic Authentication'无法在服务器VM上运行。我如何使用OAuth绕过此

windows - 尝试通过 Docker 运行 TensorFlow 时难以访问 Jupyter notebook

variables - Powershell 将变量传递给开始作业

powershell - 为什么 Powershell 中的 "New-DPMRecoveryPoint"cmdlet 缺少参数? (DPM模块)