NuGet包中的辅助函数init.ps1必须是全局的吗?

Jac*_*cob 4 powershell nuget nuget-package

我想为NuGet包管理器控制台编写几个命令,以便从GitHub插入Gists.我有4个基本命令

  • List-Gists '用户'
  • Gist- Info'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));
}
Run Code Online (Sandbox Code Playgroud)

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

dav*_*owl 7

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

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

param($installPath, $toolsPath)
Import-Module (Join-Path $toolsPath MyModule.psm1)
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

您可以在此处获取有关模块的更多信息http://msdn.microsoft.com/en-us/library/dd878340(v=VS.85).aspx