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