【问题标题】:Do helper functions in a NuGet Packages init.ps1 have to be global?NuGet Packages init.ps1 中的辅助函数是否必须是全局的?
【发布时间】:2011-03-23 14:01:43
【问题描述】:

我想为NuGet package manager 控制台编写几个命令来插入Gists from GitHub。我有 4 个基本命令

  • List-Gists '用户'
  • Gist-Info 'gistId'
  • Gist-Contents 'gistId' 'fileName'
  • 要点插入 'gistId' 'fileName'

我所有的命令都依赖于几个实用函数,我正在为它们是否需要全局而苦苦挣扎。

# Json Parser
function parseJson([string]$json, [bool]$throwError = $true) {    
    try {
        $result = $serializer.DeserializeObject( $json );    
        return $result;
    } catch {                
        if($throwError) { throw "ERROR: Parsing Error"}
        else { return $null }            
    }
}

function downloadString([string]$stringUrl) {
    try {        
        return $webClient.DownloadString($stringUrl)
    } catch {         
        throw "ERROR: Problem downloading from $stringUrl"
    }
}

function parseUrl([string]$url) {
    return parseJson(downloadString($url));
}

我可以只在我的全局函数之外拥有这些实用函数,还是需要以某种方式将它们包含在每个全局函数定义范围中?

【问题讨论】:

    标签: powershell nuget nuget-package


    【解决方案1】:

    不,他们没有。从您的 init.ps1 中,您可以导入您编写的 powershell 模块 (psm1) 文件并继续前进,这将是我们建议向控制台环境添加方法的方式。

    您的 init.ps1 看起来像这样:

    param($installPath, $toolsPath)
    Import-Module (Join-Path $toolsPath MyModule.psm1)
    

    在 MyModule.psm1 中:

    function MyPrivateFunction {
        "Hello World"
    }
    
    function Get-Value {
        MyPrivateFunction
    }
    
    # Export only the Get-Value method from this module so that's what gets added to the nuget console environment
    Export-ModuleMember Get-Value
    

    你可以在这里http://msdn.microsoft.com/en-us/library/dd878340(v=VS.85).aspx获得更多关于模块的信息

    【讨论】:

    • 很好的约定,但是有没有办法从模块中定义的函数访问 $toolsPath?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多