4

我想为NuGet 包管理器控制台编写几个命令来插入来自 GitHub 的 Gists。我有 4 个基本命令

  • List-Gists '用户'
  • 要点信息'gistId'
  • Gist-Contents 'gistId' 'fileName'
  • Gist-Insert '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));
}

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

4

1 回答 1

7

不,他们没有。从您的 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

于 2011-04-15T09:26:43.270 回答