use a script level variable to avoid invoking ImportModule repeatedly.

This commit is contained in:
Scott Beddall 2024-11-05 12:50:41 -08:00 коммит произвёл azure-sdk
Родитель 3687136d04
Коммит 322b0dbd09
1 изменённых файлов: 15 добавлений и 11 удалений

Просмотреть файл

@ -46,7 +46,9 @@ function GetDocsTocDisplayName($pkg) {
return $displayName
}
if (-not (Test-Path -Path "variable:yqPresent")) {
$script:yqPresent = $null # Initial unset state
}
<#
.SYNOPSIS
This function is a safe wrapper around `yq` and `ConvertFrom-Yaml` to convert YAML content to a PowerShell HashTable object
@ -68,7 +70,7 @@ Get-Content -Raw path/to/file.yml | CompatibleConvertFrom-Yaml
#>
function CompatibleConvertFrom-Yaml {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$Content
)
@ -76,19 +78,21 @@ function CompatibleConvertFrom-Yaml {
throw "Content to parse is a required input."
}
# Initialize any variables or checks that need to be done once
$yqPresent = Get-Command 'yq' -ErrorAction SilentlyContinue
if (-not $yqPresent) {
. (Join-Path $PSScriptRoot PSModule-Helpers.ps1)
Install-ModuleIfNotInstalled -WhatIf:$false "powershell-yaml" "0.4.1" | Import-Module
if ($null -eq $script:yqPresent) {
$script:yqPresent = [bool](Get-Command 'yq' -ErrorAction SilentlyContinue)
if (-not $script:yqPresent) {
Write-Host "yqPresent evaluated to null, then false."
. (Join-Path $PSScriptRoot PSModule-Helpers.ps1)
Install-ModuleIfNotInstalled -WhatIf:$false "powershell-yaml" "0.4.1" | Import-Module
}
}
# Process the content (for example, you could convert from YAML here)
if ($yqPresent) {
return ($content | yq -o=json | ConvertFrom-Json -AsHashTable)
if ($script:yqPresent) {
return ($content | yq -o=json | ConvertFrom-Json -AsHashTable)
}
else {
return ConvertFrom-Yaml $content
return ConvertFrom-Yaml $content
}
}