Do helper functions in a NuGet Packages init.ps1 have to be global?
-
29-10-2019 - |
Question
I'm wanting to write a couple commands for the NuGet package manager console to insert Gists from GitHub. I have 4 basic commands
- List-Gists 'user'
- Gist-Info 'gistId'
- Gist-Contents 'gistId' 'fileName'
- Gist-Insert 'gistId' 'fileName'
All of my commands depend on a couple utility functions, and I'm struggling with whether they need to be global or not.
# 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));
}
Can I just have these utility functions outside of my global functions, or will I need to include them in each of the global functions definition scope somehow?
Solution
No they don't. From your init.ps1 you can import a powershell module that you wrote (psm1) file and moving forward, this will be the way we recommend adding methods to the console environment.
Your init.ps1 would look something like this:
param($installPath, $toolsPath)
Import-Module (Join-Path $toolsPath MyModule.psm1)
In 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
You can get more information on modules here http://msdn.microsoft.com/en-us/library/dd878340(v=VS.85).aspx